Request for temporary objects

Exceptional C ++, paragraph 10, refers to the use of temporary (if you have a book, at the top of page 35 is "... namely, a copy of the returned temporary location to destination").

Code

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

I do not quite understand what time is being created where and why.

When you return an object by value from a function, is the temporary always created? Why and how much is it? In this case, s1 is copied, presumably from a temporary? Why can't it be created from a result object inside a function?

TIA

------- EDIT --------- I think I'm confused because the book uses the term copy, and using it with the meaning of the operation while I thought about it means duplicate. Verr is a good clean book in general, but this particular point may not be as clear as it may be.

+4
source share
2 answers

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

+2
source

The return value is created temporarily. Some compilers implement something called return value optimization , which avoids the extra build of the copy.

Note that the string T result = ... also creates a copy in the source code.

+1
source

Source: https://habr.com/ru/post/1336372/


All Articles