C++ mutable in D

Paul Backus snarwin at gmail.com
Sun Aug 1 12:34:27 UTC 2021


On Sunday, 1 August 2021 at 06:15:30 UTC, Jack Applegame wrote:
> On Friday, 30 July 2021 at 20:09:19 UTC, Tejas wrote:
>> Also remember that casting away const is undefined behaviour 
>> in D (unlike being defined and supported in C++).
>
> No.
> Casting const away IS NOT undefined behavior in both D and C++.
> Modifying a const object IS undefined behavior in both D and 
> C++.
> There is not much difference between D and C++ in that way.

In D, casting away const from a pointer and mutating the 
pointed-to object is UB even if the object it points to was not 
originally declared as `const` or `immutable`:

```d
int n 123; // mutable object
const(int)* pc = &n;
int* pm = cast(int*) pc;
*pm = 456; // undefined behavior
```

In C++, the above is allowed.

Source: 
https://dlang.org/spec/cpp_interface.html#comparing-d-immutable-and-const-with-cpp-const


More information about the Digitalmars-d mailing list