C++ constructor: garbage while initialization of const reference(C ++构造函数:初始化常量引用时产生垃圾)
问题描述
这段代码有什么问题,为什么我得到错误的答案:
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;
}
上面的代码会给我结果
display():a:10
display():b:1104441332
但如果我删除默认构造函数中注释的 2 行,它会给我正确的结果,即
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
请帮忙,谢谢
推荐答案
您正在初始化 b
作为对 临时的引用.
You are initializing b
as a reference to a temporary.
20
的值被创建并且只存在于构造函数的范围内.
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.
请参阅 const 引用是否会延长临时的?;答案 https://stackoverflow.com/a/2784304/383402 链接到 C++ 标准的相关部分,特别是以下文字:
See Does a const reference prolong the life of a temporary?; the answer https://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.
这就是为什么你总是在构造函数的 print 中得到正确的值,之后很少(但可能有时!).当构造函数退出时,引用悬空,所有赌注都关闭.
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 ++构造函数:初始化常量引用时产生垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C ++构造函数:初始化常量引用时产生垃圾


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01