Writing to a class member via const &

This example applies the c-style cast to int&

, followed by an assignment to the interface view of the class A

undefined?

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 name? Also, is there a reason why this compiles with no warnings? (I tested C ++ 14 on cpp.sh with -Wall, -Wextra and -Wpedantic)

+2


source to share


1 answer


const int& getX() { return x; }

      

Since this method is not marked as const, x is a volatile int. The reference is taken and cast into const int & at the return point. Note that although the reference is to const int, the actual arbiter of int is mutable. It is important.

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

      

This string returns the returned constant int int and const_cast

into an int reference. This is legal in C ++, full stop. [expr.const.cast]



However, the recording of this link is legal if the original referenced object has been modified.

In this case it is.

You will find information in [dcl.type.cv]

+8


source







All Articles