P.W
P.W

Reputation: 26800

What is unfortunate about the construction given in the following example?

Section "15.6.2 Initializing bases and members" (N4713) has the following example following item 11:

struct A {
    A() = default; // OK
    A(int v) : v(v) { } // OK
    const int& v = 42; // OK
};
A a1; // error: ill-formed binding of temporary to reference
A a2(1); // OK, unfortunately

What is unfortunate about the construction in the last line of the example?

I searched the whole reference for other occurrences of "unfortunate" behaviour that were permitted but I could find none.

If it was unfortunate in this particular context, could it not have been made illegal?

Upvotes: 4

Views: 124

Answers (1)

Jarod42
Jarod42

Reputation: 217145

In both case A::v is dangling reference (temporary from 42, or parameter v of constructor).

Having reference to temporary (even with extended lifetime) might be legal and correctly used in some cases.

Hard to detect all misuse cases to forbid them.

Upvotes: 5

Related Questions