RAII pointers

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 3 12:55:30 PDT 2017


On 06/03/2017 09:37 PM, Moritz Maxeiner wrote:
> Of course, but AFAIK you'd need to explicitly assign it to an object, so 
> `ptr` won't null by accident, but only by explicit programmer intent 
> (same as overwriting the memory the object lives in via things like 
> `memcpy`); and you can always screw things intentionally (you could also 
> assign some invalid value to the pointer via `memcpy`).

I'd say `.init` can easily happen accidentally. Especially when 
`@disable this(this);` is involved.

When you can't copy, you may have to move sometimes. But 
std.algorithm.move overwrites the old location with `.init`, assuming 
that `.init` can safely be destroyed.

----
struct S
{
     void* ptr;
     @disable this(this);
     ~this() { assert(ptr !is null); /* fails */ }
}

void f(S s) {}

void main()
{
     auto a = S(new int);
     import std.algorithm: move;
     f(move(a)); /* overwrites `a` with `S.init` */
}
----


More information about the Digitalmars-d-learn mailing list