On 7/14/16 1:46 PM, Jesse Phillips wrote:
On Thursday, 14 July 2016 at 16:47:20 UTC, Ola Fosheim Grøstad wrote:
On Thursday, 14 July 2016 at 16:17:19 UTC, Jesse Phillips wrote:
I still haven't found someone who can explain how C++ can define the
behavior of modifying a variable after casting away const.

C++ is locked down in a mine-field of backward compatibility issues
and a need to interface with C verbatim (directly including C header
files where const parameters might lack the const modifier).

D does not work with C header files and can redefine the interfaces to
fit D semantics in C bindings...

That doesn't explain how you can define the behavior:

    void foo(int const* p) {
        *(const_cast<int*>(p)) = 3;
    }

Does 'p' get modified or is the program going to crash or something
else? Please define it for me. C++ says: You can't modify the location
pointed to by 'p' from 'p', using const_cast on 'p' you'll either get
undefined behavior or it will modify the location 'p' points to. So it
is defined to either be undefined or modify the location 'p' refers to.
The language isn't able to tell you what will happen so how can it
define the behavior?

That section means the compiler will stop you from doing it unless you cast it away :)

That is:

*p = 3;

is a compiler error. That's all the note is saying.

What defining the behavior means is that the compiler has to take into account that a variable can change even though all available accesses to it are const.

For example:

int x = 5;
foo(&x);
int y = x;

If what you wrote is UB (as it is in D), then the compiler can go ahead and assign 5 to y.

In C++, the compiler has to reload x, because it may have changed.

Someone explained this to me recently on the NG.

-Steve

Reply via email to