The following code prints one
,two
, three
. Is that desired and true for all C++ compilers?
#include <iostream>
struct Foo
{
const char* m_name;
~Foo() { std::cout << m_name << '\n'; }
};
int main()
{
Foo foo{"three"};
Foo{"one"}; // unnamed object
std::cout << "two" << '\n';
}
A temporary variable lives until the end of the full expression it was created in. Yours ends at the semicolon.
This is in [class.temporary] p4:
Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.
Your behavior is guaranteed, however, the are exceptions to this rule listed in [class.temporary] p5, p6, and p7: