11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

248Part III: Introduction to ClassesThe destructor for Person now indicates that the string pointers in p1 andp2 don’t point to common block of data. (Note, again, that the destructor outputsthe most helpful “destructing...” message for debug purposes instead ofactually doing anything.It’s a Long Way to TemporariesC++ generates a copy of an object to pass to a function by value. (This isdescribed in the earlier sections of this chapter.) This is the most obvious butnot the only example. C++ creates a copy of an object under other conditionsas well.Consider a function that returns an object by value. In this case, C++ mustcreate a copy using the copy constructor. This situation is demonstrated inthe following code snippet:Student fn(); // returns object by valueint main(int argcs, char* pArgs[]){Student s;s = fn();// call to fn() creates temporary}// how long does the temporary returned by fn()last?return 0;The function fn() returns an object by value. Eventually, the returned objectis copied to s, but where does it reside until then?C++ creates a temporary object into which it stuffs the returned object. “Okay,”you say. “C++ creates the temporary, but how does it know when to destructit?” Good question. In this example, it doesn’t make much difference, becauseyou’ll be through with the temporary when the copy constructor copies itinto s. But what if s is defined as a reference:int main(int argcs, char* pArgs[]){Student& refS = fn();// ...now what?...return 0;}It makes a big difference how long temporaries live because refS exists for theentire function. Temporaries created by the compiler are valid throughout theextended expression in which they were created and no further.In the following function, I mark the point at which the temporary is no longervalid:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!