If changing a const object is undefined behavior then how do constructors and destructors operate with write access?

前端 未结 5 1589
名媛妹妹
名媛妹妹 2020-12-11 03:48

C++ standard says that modifying an object originally declared const is undefined behavior. But then how do constructors and destructors operate?



        
5条回答
  •  一个人的身影
    2020-12-11 03:53

    Here's a way that ignoring the standard could lead to incorrect behavior. Consider a situation like this:

    class Value
    {
        int value;
    
    public: 
        value(int initial_value = 0)
            : value(initial_value)
        {
        }
    
        void set(int new_value)
        {
            value = new_value;
        }
    
        int get() const
        {
            return value;
        }
    }
    
    void cheat(const Value &v);
    
    int doit()
    {
        const Value v(5);
    
        cheat(v);
    
        return v.get();
    }
    

    If optimized, the compiler knows that v is const so could replace the call to v.get() with 5.

    But let's say in a different translation unit, you've defined cheat() like this:

    void cheat(const Value &cv)
    {
         Value &v = const_cast(cv);
         v.set(v.get() + 2);
    }
    

    So while on most platforms this will run, the behavior could change depending on what the optimizer does.

提交回复
热议问题