Search code examples
c++constantsg++visual-studio-2019volatile

Changing value of volatile const - G++ vs Visual Studio 2019


So I have a following snippet (and a good reason behind it):

#include <iostream>

volatile const float A = 10;

int main() {
    volatile const float* ptr = &A;
    float* safePtr = const_cast<float*>(ptr);
    *safePtr = 20;

    std::cout << A << std::endl;

    return 0;
}

Under G++ v8.2.0 (from MinGW suite), this program compiles fine and outputs 20 as expected. Under VS2019, it compiles, but throws a runtime exception - Exception thrown at 0x00007FF7AB961478 in Sandbox.exe: 0xC0000005: Access violation writing location 0x00007FF7AB969C58.

Is there a way to make VS2019 behave the same way the G++ does? And how to do it with CMake?


Solution

  • All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS.


    As governed by [dcl.type.cv]/4, your program has undefined behaviour

    Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior. [ Example:

    // ...
    
    const int* ciq = new const int (3);  // initialized as required
    int* iq = const_cast<int*>(ciq);     // cast required
    *iq = 4;                             // undefined: modifies a const object
    

    and as such, demons may fly out of your nose and any kind of analysis of your program beyond this point, including comparison of the behaviour for different compilers, will be a fruitless exercise.