我读过很多关于临时对象生命周期的文章,似乎临时对象的生命周期在某些情况下会延长,而在其余情况下,它是一个悬空对象。
在我的例子中,临时对象是从函数返回的,我想了解临时对象的 const ref 是否仍然有效。
代码如下:
class MyClass
{
public:
std::vector<int> vec{ 1, 2 };
MyClass()
{
cout << "Ctor" << endl;
}
MyClass(const MyClass ©)
{
vec = copy.vec;
cout << "Copy Ctor" << endl;
}
~MyClass()
{
cout << "Dtor" << endl;
}
};
MyClass access()
{
MyClass obj;
obj.vec[0] = 10;
return obj;
}
int main()
{
{
const auto &ret = access(); // calls the copy-ctor and assigns the temporary to reference 'ret'
auto val = ret.vec[0];
cout << "By Ref = " << val << endl; // works fine
}
cout << "_____________________________________" << endl;
{
const auto *ret = &access(); // temporary is lost
auto val = ret->vec[0]; // program crash
cout << "By Pointer = " << val << endl;
}
return 0;
}
最佳答案
只有绑定(bind)到 const 引用的临时对象的生命周期才会延长,除了绑定(bind)到函数返回的 const 引用,例如
const int& f(){int x{42}; return x;}
int main()
{
const int& bad = f(); // you'll end up with a dangling reference
}
或
const int& f(const int& x)
{
return x;
}
int main(){
{
const int& bad = f(42); // you'll end up (again) with a dangling reference
}
在第二种情况下,您有一个指针,因此不会延长右侧临时对象的生命周期。
关于c++ - 引用临时与指向临时及其生命周期的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103262/