C++: if mutable must be visible and modifying a const_cast’d object is UB, why doesn’t const improve performance?

  c++, const-cast, constants, mutable

I don’t understand how the following statements can be simultaneously correct:

  1. Modifying an const object where the const has been const_casted away is undefined behaviour.
  2. const qualifications don’t help the compiler generate more efficient code. Cf: GotW#81, Can const-correctness improve performance? and many others.

From what I understand the rationale here is that either the compiler knows what the code is during optimization, in which case it can act based on whether the object actually modifies the object or not, or it doesn’t know, and even if a const qualifier is exposed, that hardly matters because const_cast, mutable, and more simply void* fuckery exists.

But, mutable is visible in header files. Modifying a const object through a const_cast is undefined behaviour. I assume that modifying a const object through other means (raw memory writes and the likes) is also undefined behaviour.

So then, if we know the definition of a class but not the definition of its functions at optimization time and one of these functions takes a const ref, why can’t the compiler assume this function doesn’t modify the object.

To give a concrete example:

// SomeStruct is a plain but heavy class

void dynamicallyLinkedFunction(const SomeStruct &someStruct);

void callDynamicallyLinkedFunctionWithACopy(SomeStruct someStruct) {
    dynamicallyLinkedFunction(someStruct);
}

void foo() {
    const SomeStruct someStruct;
    callDynamicallyLinkedFunctionWithACopy(someStruct);
    /* Do things with someStruct */
}

In this case, doesn’t the fact that dynamicallyLinkedFunction takes a const ref allow removing the copy of someStruct done by callDynamicallyLinkedFunctionWithACopy ?

I would expect the compiler to consider that the body of callDynamicallyLinkedFunctionWithACopy doesn’t actually modify the passed object, and act upon that.

Source: Windows Questions C++

LEAVE A COMMENT