Where are temporary object stored?
The standard does not mandate any memory area (heap/stack) for them, but they are just like local variables "automatic storage", that is at the end of the expression (or longer when bound to a ref-to-const) they are destructed.
Most implementations will store them on the stack just like local variables.
edit:
As James Kanze pointed out: In the case the lifetime of a temporary is extended via a ref-to-const, its store location is on most implementations somewhat determined by the storage location of that reference. That is, in the case of the reference being in static storage, the temporary will be too (just confirmed on gcc). (although IMHO while this is still a temporary in the standards sense, it is arguable whether this is a temporary in the intuitive english sense of that word)
It depends on their lifetime. Temporaries you create inside of a function that you dont bind to a local static reference to lengthen their lifetime will most likely be created on the stack. Temporaries you bind to local static references will most likely be stored in the .data section of your program binary. Same holds for temporaries you bind to nonlocal references. Temporaries that are created during initialization of a nonlocal variable other that the one bound to by a reference should be on the stack of the function that produces the value of that nonlocal variable.
Exception objects that represent the thrown object during unwinding are temporaries too. Those usually reside on the heap.
This is highly implementation dependent, but they probably reside in automatic storage.
Note that the scope can be counter-intuitive, because of optimizations.
The following:
class A
{
//...
};
//....
A foo()
{
A a;
return a;
}
Here, the object a
doesn't necessarily reside only inside the function's scope, but RVO can occur.
Also, when passing by value a temporary object, it might not get destructed immediately.
void foo(A a);
//...
foo( A() );
Here, a temporary is not necessarily only alive in that line, but can be constructed directly inside the method's argument stack.