const member and assignment operator. How to avoid the undefined behavior?

前端 未结 8 1689
别跟我提以往
别跟我提以往 2020-12-05 17:14

I answered the question about std::vector of objects and const-correctness, and received a comment about undefined behavior. I do not agree and therefore I have a question.<

8条回答
  •  無奈伤痛
    2020-12-05 18:07

    If you definitely want to have an immutable (but assignable) member, then without UB you can lay things out like this:

    #include 
    
    class ConstC
    {
        int c;
    protected:
        ConstC(int n): c(n) {}
        int get() const { return c; }
    };
    
    class A: private ConstC
    {
    public:
        A(int n): ConstC(n) {}
        friend std::ostream& operator<< (std::ostream& os, const A& a)
        {
            return os << a.get();
        }
    };
    
    int main()
    {
        A first(10);
        A second(20);
        std::cout << first << ' ' << second << '\n';
        first = second;
        std::cout << first << ' ' << second << '\n';
    }
    

提交回复
热议问题