Writing to class member through const &

白昼怎懂夜的黑 提交于 2019-12-11 03:39:17

问题


In this example, is the c-style cast to int& followed by an assignment to kind of hack the interface of class A undefined behavior?

class A
{
public:
    A()
    : x(0)
    {
    }

    ~A()
    {
        std::cout << x << std::endl;
    }

    const int& getX()
    {
        return x;
    }

private:
    int x;
};

int main()
{
    A a;
    int& x = (int&)a.getX();
    x = 17;
    std::cout << x << std::endl;
}

Output:

17
17

If so, what part of the standard can i refer to? Also, is there any reason why this compiles without warnings? (i tested with c++14 on cpp.sh with -Wall, -Wextra and -Wpedantic)


回答1:


const int& getX() { return x; }

Since this method is not marked const, x is a mutable int. A reference is taken and cast to a const int& at the point of return. Note that although the reference is to a const int, the actual referee int is mutable. This is important.

int& x = (int&)a.getX();

This line takes the returned const int reference and const_cast's it to an int reference. This is legal in c++, full stop. [expr.const.cast]

However, writing through this reference is only legal if the original object being referenced is mutable.

In this case, it is.

You will find the details in [dcl.type.cv]



来源:https://stackoverflow.com/questions/43684754/writing-to-class-member-through-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!