David Preston
David Preston

Reputation: 2071

Query about temporary objects

In Exceptional C++, item 10, its talking about use of a temporary (if you have the book, top of page 35 "... namely, the copy of the returned temporary into the destination").

The code is

template<class T>
T Stack::<T>::Pop()
{
...
T result = ...
return result;
}

...


string s1(s.Pop());

I'm not quite clear on what temporary is being created where and why.

When you return an object by value from a function is a temporary always created? Why and what's its scope? In this case s1 is being copy constructed, presumably from the temporary? Why can it not be constructed from the result object within the function?

TIA

------- EDIT --------- I think I got confused because the book is using the term copy, and its using it with the meaning of an operation while I was thinking of it meaning duplicate. Verr good clear book in general, but this particular paragraph perhaps isn't as clear as it could be.

Upvotes: 4

Views: 142

Answers (2)

Charles Salvia
Charles Salvia

Reputation: 53289

The unnamed return value of the function is the temporary. It's created as a return value of the function, and then passed to the copy constructor of the string, and then promptly destroyed.

Upvotes: 2

ChrisV
ChrisV

Reputation: 3423

The return value is the temporary being created. Some compilers implement something called return value optimization that avoids the extra copy construction.

Note that the T result = ... line also creates a copy in the original text.

Upvotes: 1

Related Questions