我发现当临时对象绑定(bind)到一个类的实例时,我使用 g++-4.8.1 获得了以下 2 个示例的不同行为:
template <class T>
struct A
{
A(T const& a) : b(a) { }
T const& b;
};
和
template <class T>
struct B
{
B(T const& a) : b{a} { }
T const& b;
}
我发现,对于第一个示例,绑定(bind)的临时对象在 A 的实例的生命周期内持续存在,但 B 的实例并非如此。根据 C++11,这种行为是否正确标准?请指出标准的相关部分。
注意:
A
和 B
以及它们绑定(bind)的临时对象在表达式中实例化。在表达式的末尾,它们连同它们绑定(bind)的临时对象一起被销毁,这就是为什么它们的生命周期应该与临时对象的生命周期相同。
编辑:标准的这一部分能否解释两个初始化之间的差异:
— 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 ]
最佳答案
这样的行为是不正确的。请参阅 8.5.4p3 第 4 个最后一个项目符号。一段时间以来,准标准草案就是这种情况,但在 C++11 中并非如此。
看来您很困惑:在任何情况下都不应创建临时文件。这两种情况都应该用另一个引用初始化一个引用。只有在第二种情况下,一些预标准草案说应该创建一个临时的并绑定(bind)到成员引用,而不是直接初始化引用。
(参见 this list 中的第 27 条)。
关于c++ - 对临时对象的 const 引用的列表初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17382796/