简体   繁体   中英

Where are temporary objects allocated in C++?

SomeClass a, b, c;
SomeClass foo();
SomeClass a = (b + c); //Where is the object (b + c) allocated?
SomeClass a = foo(); //Where is the returned value of foo() allocated?

My guess is that they are allocated on the heap because I read that temporary objects are destroyed at the end of the expression(;).

It makes sense to me because the move constructor could be implemented by stealing the pointer of the temporary object on the heap.

If created at all (consider optimizations), they're in automatic storage . Ie the stack.

Generally, if there's a destination for the temporary object, it can be created there. Even stronger, that can be true even if the temporary has a different type: Foo f = transmogrify(Bar()); - the Bar() temporary can probably steal the storage needed for f .

There's a theoretical model when destructors run, but often that's not observable behavior and therefore optimizable. Ie many dtors can run early.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM