C++构造函数:初始化const引用时的垃圾

Viv*_*ppa 21 c++ constructor 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;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码会给我结果

display():a:10
display():b:1104441332
Run Code Online (Sandbox Code Playgroud)

但是如果我删除默认构造函数中的注释2行,它给出了正确的结果

constructor : a 10
constructor : b 20
display():a:10
display():b:20
Run Code Online (Sandbox Code Playgroud)

请帮忙,谢谢

Bor*_*lid 24

您正在初始化b临时的参考.

该值20已创建,仅存在于构造函数的范围内.

在此之后代码的行为非常有趣 - 在我的机器上,我从你发布的那些中得到不同的值,但基本行为仍然是不确定的.

这是因为当引用点超出范围的值时,它开始引用垃圾内存,从而产生不可预测的行为.

请参阅const引用是否延长了临时的寿命?; 答案/sf/answers/194901311/链接到C++标准的相关部分,特别是以下文本:

A temporary bound to a reference member in a constructor’s ctor-initializer
(12.6.2) persists until the constructor exits.
Run Code Online (Sandbox Code Playgroud)

这就是为什么你总是在构造函数中的print中获得正确的值,并且很少(但有时可能!)之后.当构造函数退出时,引用悬​​空并且所有下注都关闭.


R. *_*des 19

我会让我的编译器回答这个问题:

$ g++ -std=c++98 -Wall -Wextra -pedantic test.cpp
test.cpp: In constructor 'X::X()':
test.cpp:9:26: warning: a temporary bound to 'X::b' only persists until the constructor exits [-Wextra]
$
Run Code Online (Sandbox Code Playgroud)

您也应该打开编译器上的警告.