IMO temporary objects are stored in dynamic (heap) memory, but I'm not sure. Can you please confirm or deny my thoughts?
问题:
回答1:
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)
回答2:
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.
回答3:
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.
回答4:
Most (if not all) implementations store them on the stack (i.e. automatic storage), although I don't think the standard mandates anywhere. It's certainly easier to do it like that, as the compiler has to guarantee the temporary variable's life time, and it is possible that said lifetime will encompass a recursive call of the same function, creating another instance of the temporary variable.