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

走远了吗. 提交于 2021-01-03 05:48:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!