以下示例给出的构造有什么不幸? [英] What is unfortunate about the construction given in the following example?
问题描述
"15.6.2初始化基和成员"(N4713)节具有以下第11项的示例:
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?
推荐答案
在两种情况下, A :: v
都是悬空引用(临时取自42,或者是参数 v
的构造函数).
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.
这篇关于以下示例给出的构造有什么不幸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!