An Optional!T and the implementation of the underlying type's opUnary
Simen Kjærås
simen.kjaras at gmail.com
Fri Jul 27 14:15:24 UTC 2018
On Friday, 27 July 2018 at 12:52:09 UTC, aliak wrote:
> On Thursday, 26 July 2018 at 06:37:41 UTC, Simen Kjærås wrote:
>> As for assigning to Optional!(immutable int), the language
>> basically forbids this (cannot modify struct with immutable
>> members). It would, as you say, cause problems when you can
>> get a pointer to the contents.
>
> So is this undefined behaviour?
>
> import std.stdio;
>
> struct S(T) {
> T value;
> void opUnary(string op)() inout {
> mixin(op ~ "cast(T)value;");
> }
> }
>
> void main() {
> immutable a = S!int(2);
> ++a;
> }
It's the exact same as the top two lines of this:
void main() {
immutable int a = 2;
++*cast(int*)&a;
assert(a == 3); // Will trigger on DMD 2.081.1
}
So yes, it's casting away immutable and modifying it, which is UB.
--
Simen
More information about the Digitalmars-d
mailing list