问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/52147940/what-is-unfortunate-about-the-construction-given-in-the-following-example