Reference argument to operator =

greenspun.com : LUSENET : Steve Heller's books : One Thread

In your book THE C++ TRAINING GUIDE, you create a string class as an example. In describing, in chapter 8, why we needed to use a reference argument to the operator = instead of a value argument, you state that the compiler - generated copy constructor will wipe out the caller's pointed-to-data when the temporary is destroyed at the end of its scope.

While this is true, and certainly a danger, isn't this entirely obviated by the fact that we have a perfectly good copy constructor provided in the previous chapter? One that doesn't just copy the pointer itself but also the refered-to-data? I don't see how there would be any danger in that at all as long as a well thought out copy constructor is available. Or would this not be used to create the temporary? Or are you just trying to get us into good programming habits? Or did I just demonstrate that I've missed half the book? I don't fully follow. Please help.

-- Mike Mannakee (B3FEETBACK@aol.com), May 09, 1999

Answers

Yes, the copy constructor that we've already written does prevent that particular danger in this case. However, there is another reason that we have to use a reference argument to operator = rather than a value argument: calling the copy constructor to make a copy creates a great deal of additional work to be performed for no reason. As a thought experiment, try to figure out all the function calls that would be executed in the processing of the statement "a = b;" if operator= used a value argument. For extra credit, figure out what would happen if the statement "a=a;" were executed under the same conditions.

-- Steve Heller (stheller@koyote.com), May 09, 1999.

Moderation questions? read the FAQ