According to http://dlang.org/const3.html any modification of immutable data causes undefined behaviour. Now I want to initialise a struct with immutable members in some malloc'd memory and found the emplace function. I came up with the following code:

import core.stdc.stdlib;

import std.conv;

struct Point {
 immutable double x;
 immutable double y;
}

void main() {
 void* a = malloc(Point.sizeof);
 Point* p = cast(Point*) a;
 emplace!Point(p, 1.0, 2.0);
}

this compiles and runs fine. Because emplace expects a typed pointer, it actually modifies (*p).x and (*p).y
As far as I understand, this causes undefined behavior.

Are there any (safe) alternatives to this code other than making the immutable members mutable?

Reply via email to