0
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.

trincot
  • 317,000
  • 35
  • 244
  • 286
Kami
  • 1,079
  • 2
  • 13
  • 28
  • The fact that they are destroyed doesn't say anything about whether they are allocated on the heap or the stack. Objects allocated on the stack are also destroyed (i.e. their destructor is called) at some point. – Jesper Jun 26 '14 at 10:52
  • *"My guess is that they are allocated on the heap because I read that temporary objects are destroyed at the end of the expression(;)."* -- I don't follow this logic. The usefulness of dynamic allocation ("on the heap") comes when you want the object to live a relatively long time. That's how you get an object to outlive the function in which it is created. The fact that these objects are destroyed very quickly -- faster then many local variables -- suggests non-dynamic allocation to me. – JaMiT Jun 15 '22 at 03:34

2 Answers2

4

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

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

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. I.e. many dtors can run early.

MSalters
  • 173,980
  • 10
  • 155
  • 350