Specifically, is the following legal C++?
class A{}; void foo(A*); void bar(const A&); int main(void) { foo(&A()); // 1 bar(A()); // 2 }
It a
Short answer is yes.
If the object is received by function as const reference parameter - as you have modified bar(const A&)
method, then it's totally legal. The function can operate on the object, but the object will be destructed after the function call (address of temporary can be taken, but shall not be stored and used after the function call - see reason below).
The foo(A*)
is legal too because the temporary object is destroyed at the end of fullexpression. However most of the compiler will emit warning about taking address of temporary.
The original version of bar(A&)
shall not compile, it's against the standard to initialize a non-const reference from a temporary.
C++ standard chapter 12.2
3 [...] Temporary objects are destroyed as the last step in evaluating the fullexpression (1.9) that (lexically) contains the point where they were created. [...]
4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when an expression appears as an initializer for a declarator defining an object. In that context, the temporary that holds the result of the expression shall persist until the object’s initialization is complete. [...]
5 The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctorinitializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call. A temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits.
A fullexpression is an expression that is not a subexpression of another expression.