Search code examples
c++constantsundefined-behaviorconst-correctnessconst-cast

Why is writing to a non-const object after casting away const of pointer to that object not UB?


According to the C++ Standard it's okay to cast away const from the pointer and write to the object if the object is not originally const itself. So that this:

 const Type* object = new Type();
 const_cast<Type*>( object )->Modify();

is okay, but this:

 const Type object;
 const_cast<Type*>( &object )->Modify();

is UB.

The reasoning is that when the object itself is const the compiler is allowed to optimize accesses to it, for example, not perform repeated reads because repeated reads make no sense on an object that doesn't change.

The question is how would the compiler know which objects are actually const? For example, I have a function:

void function( const Type* object )
{
    const_cast<Type*>( object )->Modify();
}

and it is compiled into a static lib and the compiler has no idea for which objects it will be called.

Now the calling code can do this:

Type* object = new Type();
function( object );

and it will be fine, or it can do this:

const Type object;
function( &object );

and it will be undefined behavior.

How is compiler supposed to adhere to such requirements? How is it supposed to make the former work without making the latter work?


Solution

  • When you say "How it is supposed to make the former work without making the latter work?" an implementation is only required to make the former work, it needn't - unless it wants to help the programmer - make any extra effort in trying to make the latter not work in some particular way. The undefined behavior gives a freedom to the implementation, not an obligation.

    Take a more concrete example. In this example, in f() the compiler may set up the return value to be 10 before it calls EvilMutate because cobj.member is const once cobj's constructor is complete and may not subsequently be written to. It cannot make the same assumption in g() even if only a const function is called. If EvilMutate attempts to mutate member when called on cobj in f() undefined behavior occurs and the implementation need not make any subsequent actions have any particular effect.

    The compiler's ability to assume that a genuinely const object won't change is protected by the fact that doing so would cause undefined behavior; the fact that it does, doesn't impose additional requirements on the compiler, only on the programmer.

    struct Type {
        int member;
        void Mutate();
        void EvilMutate() const;
        Type() : member(10) {}
    };
    
    
    int f()
    {
        const Type cobj;
        cobj.EvilMutate();
        return cobj.member; 
    }
    
    int g()
    {
         Type obj;
         obj.EvilMutate();
         return obj.member; 
    }