【发布时间】:2018-06-06 15:27:59
【问题描述】:
我想知道下一个代码是否可以正确使用 v 和 v2 变量,或者这些是临时变量的引用?换句话说,我可以通过引用捕获返回的右值吗?我不认为,但我的团队负责人有不同的想法。
#include <iostream>
struct Foo {
Foo(Foo&&) = delete;
Foo& operator=(Foo&&) = delete;
Foo() {
std::cout << "Constructor" <<std::endl;
}
Foo(const Foo&) {
std::cout << "Copy Constructor" <<std::endl;
}
Foo& operator=(const Foo&) {
std::cout << "Copy = Constructor" <<std::endl;
return *this;
}
~Foo() {
std::cout << "Destructor" <<std::endl;
}
};
Foo foo() {
Foo v;
return v;
}
int main() {
const auto& v = foo();
const auto& v2 = v;
return 0;
}
【问题讨论】:
-
我的意思是……把它扔进编译器,看看它说了什么?
-
它工作正常,但对我来说似乎 v 和 v2 变量捕获临时值的引用,这意味着导致 SEGFAULT
-
将临时对象绑定到 const 引用会将临时对象的生命周期延长到引用的生命周期。
标签: c++ c++11 reference lifetime const-reference