Search code examples
c++constantsundefined-behaviorconst-cast

Casting away const-ness of method


As a follow up to my previous question (Writing to class member through const &), is it also well defined and correct to cast away a class member method's const-ness like this?

class A
{
public:
    A()
    : a(5)
    {
    }

    int run() const
    {
        std::cout << "a: " << a << std::endl;
        int& x = (int&)a;
        x = 17;
        std::cout << "a: " << a << std::endl;
        return 0;
    }

private:
    int a;
};

int main()
{
    A program;
    return program.run();
}

Output (tested with c++14 on cpp.sh with -O0, -Wall, -Wextra and -Wpedantic):

a: 5
a: 17

If not, what part of the standard would i refer to for an explanation?


Solution

  • Yes, your code is valid, although not recommended, as long as the object instance you start with is non-const (which is the case in your code, A program; is non-const).

    Removing const-ness from a const instance is UB (undefined behaviour). Removing const-ness from a casted-to-const initial non-const instance is well defined, see e.g. the documentation for const_cast.

    If you really need to modify a member variable from a const member function, consider marking the former as mutable. Otherwise your current technique will lead to UB whenever someone (by mistake) invokes your member function on a const instance.