Is there a way to see if .init has been set by the user?

Maxim Fomin maxim at maxim-fomin.ru
Sat Sep 21 08:47:48 PDT 2013


On Saturday, 21 September 2013 at 11:35:11 UTC, bearophile wrote:
>
> init is part of a type and you can't change it.
>
> Bye,
> bearophile

Well, D wouldn't be D, if it did not allow something like this 
for aggregate types:

import core.stdc.string, std.stdio;

pure hack(T)(T value) if (is(T == class))
{
     byte[] init_mem = new byte[T.classinfo.init.length];
     memcpy(init_mem.ptr, cast(byte*)value, 
T.classinfo.init.length);
     T.classinfo.init = init_mem;
}

class A
{
    int a;
}

pure foo(int val)
{
    A a = new A;
    a.a++;
    hack(a);
    return a.a + val;
}

void main()
{
    writeln(0.foo, 0.foo, 0.foo); // prints 1,2,3
}

And taking into accout some additional runtime magic, assertion 
below may fail:

class A { int i = 5; }
struct S { A a;}
S s;
assert(s.a is null);


More information about the Digitalmars-d-learn mailing list