C ++构造函数:初始化const引用时的garbage [英] C++ constructor: garbage while initialization of const reference
问题描述
这段代码有什么问题,为什么我会得到错误的答案:
class X
{
private:
const int a;
const int& b;
public:
X():a(10),b(20)
{
// std :: cout< constructor:a< a<< std :: endl;
// std :: cout<< constructor:b< b<< std :: endl;
}
void display()
{
std :: cout< display():a:<< a<< std :: endl;
std :: cout<< display():b:< b<< std :: endl;
}
};
int
main(void)
{
X x;
x.display();
return 0;
}
上述代码将结果显示为
display():a:10
display():b:1104441332
但是如果我删除在默认构造函数中注释的两行,它给我正确的结果是
构造函数:a 10
构造函数:b 20
display():a:10
display():b:20
请帮助,谢谢。
解决方案您正在初始化
b
作为对临时的引用。
值<$
这段代码之后的行为非常有趣 - 只有在构造函数的作用范围内才会创建
20 在我的机器上,我从你发布的值得到不同的值,但基本的行为仍然是不确定的。
这是因为当参考点的值
请参阅 http://stackoverflow.com/a/2784304/383402 链接到C ++标准的相关部分,具体来说以下文本:
临时绑定到构造函数的ctor-initializer中的引用成员
(12.6.2)持续到构造函数退出。
这就是为什么你总是在构造函数中打印正确的值,很少有时!)后。当构造函数退出时,引用悬挂和所有注单都关闭。
what is wrong with this code, why do I get wrong answer:
class X { private: const int a; const int& b; public: X(): a(10) , b(20) { // std::cout << "constructor : a " << a << std::endl; // std::cout << "constructor : b " << b << std::endl; } void display() { std::cout << "display():a:" << a << std::endl; std::cout << "display():b:" << b << std::endl; } }; int main(void) { X x; x.display(); return 0; }
The above code will give me the result as
display():a:10 display():b:1104441332
But If I remove the commented 2 lines inside the default constructor it gives me proper result which is
constructor : a 10 constructor : b 20 display():a:10 display():b:20
please help, Thank you
解决方案You are initializing
b
as a reference to a temporary.The value
20
is created and exists only for the scope of the constructor.The behavior of the code after this is very interesting - on my machine, I get different values from the ones you posted, but the fundamental behavior is still nondeterministic.
This is because when the value to which the reference points falls out of scope, it begins to reference garbage memory instead, giving unpredictable behavior.
See Does a const reference prolong the life of a temporary?; the answer http://stackoverflow.com/a/2784304/383402 links to the relevant section of the C++ standard, specifically the below text:
A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
This is why you always get the right value in the print within the constructor, and rarely (but possibly sometimes!) after. When the constructor exits, the reference dangles and all bets are off.
这篇关于C ++构造函数:初始化const引用时的garbage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!