C++ constructor: garbage while initialization of const reference

前端 未结 4 770
陌清茗
陌清茗 2020-12-15 18:45

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)         


        
4条回答
  •  情歌与酒
    2020-12-15 19:22

    b refers to a temporary. What you have read (when printing) is an invalid location by the time it is read since the temporary 20 has technically gone out of scope.

    To explain inconsistent results:

    It is undefined behavior. What you see may be different if you:

    • change your compiler
    • change your compiler settings
    • build for another architecture
    • change your class' member layout
    • add or remove things from the memory region near the instance of x
    • etc.

    You should always always avoid undefined behavior.

    But why would the value change? Your reference likely refers to a stack address which has been rewritten (e.g. reused) by the time it's printed.

提交回复
热议问题