I find I am getting different behaviors for the 2 samples below with g++-4.8.1, when temporaries are bound to an instance of a class:
template <class T>
struct A
{
A(T const& a) : b(a) { }
T const& b;
};
and
template <class T>
struct B
{
B(T const& a) : b{a} { }
T const& b;
}
I find, for the first sample, a bound temporary object persists for the life-time of an instance of A, but this is not the case for an instance of B. Is such behavior correct according to the C++11 standard? Please point to the relevant parts of the standard.
NOTE:
A
and B
, as well as the temporaries they bind to are instantiated in an expression. At the end of the expression, they are destroyed, along with the temporary they bind to, that is why their life-time should be the same as the life-time of the temporary.
EDIT: Could this part of the standard explain the discrepancy between the 2 initializations:
— Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is list-initialized, and the reference is bound to that temporary. [ Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type. — end note ]
B
. – Casey