[英]Lifetime of const reference variable not extended
Binding a temporary to a const reference extends its lifetime; 将临时绑定到const引用可以延长其寿命; cf. cf. GotW #88 . 得到#88 。
Why does not this work on this snippet? 为什么此代码段不起作用? Live here . 住这里 。
#include <iostream>
#include <string>
struct A {
A() : s("abc") {}
const std::string& s;
};
struct B {
const std::string& s = "def";
};
int main() {
A a;
std::cout << a.s << std::endl;
B b;
std::cout << b.s << std::endl;
}
Bonus question: How to trigger a warning with gcc? 奖励问题:如何使用gcc触发警告?
In the article that you linked to, you will find: 在链接到的文章中,您将找到:
(Note this only applies to stack-based references. It doesn't work for references that are members of objects.) (请注意,这仅适用于基于堆栈的引用。不适用于属于对象成员的引用。)
That's why the references in a
and b
are not valid. 这就是为什么a
和b
中的引用无效的原因。 They don't extend the life of the temporaries. 他们不会延长临时人员的寿命。
From C++14 [class.temporary]/5: 从C ++ 14 [class.temporary] / 5:
The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except : 引用所绑定的临时对象或引用所绑定的子对象的完整对象的临时对象在引用的生存期内一直存在, 但以下情况除外 :
A temporary bound to a reference member in a constructor's ctor-initializer persists until the constructor exits. 在构造函数的ctor-initializer中 ,与引用成员的临时绑定将一直保留,直到构造函数退出。
[...] [...]
cppreference.com says: cppreference.com说:
a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists. 构造函数初始化器列表中与引用成员的临时绑定仅在构造函数退出之前一直存在,而不管对象是否存在。
http://en.cppreference.com/w/cpp/language/reference_initialization http://en.cppreference.com/w/cpp/language/reference_initialization
The lifetime is only extended to the end of the compiler generator constructor for B
. 生存期仅延长至B
的编译器生成器构造函数的末尾。 When the constructor returns, the temporary string created to hold "def" will be destroyed leaving you with a dangling reference. 当构造函数返回时,为保存“ def”而创建的临时字符串将被销毁,从而留下悬挂的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.