即使这个主题在这里讨论了很多次,我也找不到关于我的具体案例的结论性解释。 const
会临时延长 RefTest
的生命周期吗?下面的例子合法吗?
#include <iostream>
class RefTest
{
public:
RefTest(const std::string &input) : str(input) {}
~RefTest () {std::cout << "RefTest" << std::endl;}
private:
std::string str;
};
class Child
{
public:
Child (const RefTest &ref) : ref_m(ref) {}
~Child () {std::cout << "Test" << std::endl;}
private:
const RefTest &ref_m;
};
class Test
{
public:
Test () : child(RefTest("child")) {}//Will the temporary get destroyed here?
~Test () {std::cout << "Test" << std::endl;}
private:
const Child child;
};
int main ()
{
Test test;
}
最佳答案
引用不会延长生命周期。该代码是合法的,但这只是因为在构造函数完成后您永远不会访问 ref_m
。
临时绑定(bind)到构造函数参数 ref
。稍后将另一个引用绑定(bind)到它,ref_m
,不会延长生命周期。如果是这样,您将在堆栈上有一个对象,只要它绑定(bind)到引用成员,它就必须持续存在,可以在堆上分配,因此编译器将无法在构造函数返回时展开堆栈。
如果能得到警告就好了,但编译器并不完美,有些事情很难发出警告。临时文件是在与绑定(bind)到引用的上下文不同的上下文中创建的,因此编译器只能判断打开的内联有问题,或者一些聪明的静态分析。
关于c++ - 作为类成员的常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513734/