【发布时间】:2013-03-08 23:14:11
【问题描述】:
即使这个话题在这里讨论过很多次,我也找不到关于我的具体案例的结论性解释。 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;
}
【问题讨论】:
-
最后一行根本没有创建对象。它正在声明一个函数。见en.wikipedia.org/wiki/Most_vexing_parse。
-
@OliCharlesworth 哦,开枪。我担心这个例子很愚蠢:(请看我更新的那个,应该更接近我的真实情况。这一次,我不认为应该有任何令人烦恼的解析问题。
-
@NayanaAdassuriya 哪个
test2?我重写了我最初的例子,因为我没有考虑足够的想法。 -
@carleeto 是的,Haroogan 已经链接了它。谢谢。
标签: c++ class reference constants member