2
votes

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 ]

2
Could you perhaps provide a complete example?Some programmer dude
The complete example is an expression template class, it would be very long. Replacing { } with ( ) makes the expression template library work.user1095108
@JoachimPileborg Example at ideone that demonstrates that g++-4.7.2 creates a temporary for B.Casey
This is GCC bug 50025.Casey

2 Answers

4
votes

Such behavior is not correct. See 8.5.4p3 4rd last bullet. This was the case for pre-standard drafts for some time, but is not the case in C++11.

It seems you are confused: In no case there should a temporary be created. Both cases should initialize a reference with another reference. Only in the second case, some pre-standard drafts said that a temporary should be created and bound to the member reference, instead of initializing the reference directly.

(See Number 27 in this list).

2
votes

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?

The behaviour of B is correct. But the behaviour of A is wrong in that the life-time of the temporary should not persist till the life-time of object of A (or the life-time of B in case of B).

But as a sidenote, since you're binding a temporary to the member of B, be aware! The temporary doesn't exist when the constructor returns, which means what the member refers to, doesn't exist!