Consider the following code:
class Test() {
public:
Test()
{
memset( buffer, 0, sizeof( buffer ) );
}
void Process()
{
printf( buffer );
}
private:
char buffer[1000];
};
int main()
{
Test().Process();
char buffer[1000] = {};
print( buffer );
return 0;
}
I can’t deduce whether buffer in main is allowed to reuse the memory previously occupied by the temporary object of class Test. According to The Standard automatic storage (3.7.2/1) must persist for at least until the block ends.
I can’t find phrasing that would force a temporary object to use automatic storage except 6.6/2 where a jump statement is described and says that on exit from a scope […], destructors (12.4) are called for all constructed objects with automatic storage duration (3.7.2) (named objects or temporaries) which seems to imply that temporaries use automatic storage.
Are temporaries required to use automatic storage? Is the local variable in main in code above allowed to reuse the memory previously occupied by the temporary or should it use distinct storage?
The lifetime of the temporary (unless bound to a
const&) extends to the end of the full expression. In your case the first line inmain. The compiler is allowed to reuse the same memory, but whether it does or not is an implementation detail (i.e. quality of implementation)Since you are in neither exception, the
Testtemporary falls into the first category and is destroyed as the last step of the evaluation of that first line.