structs holding on to reference data by pointer

bearophile bearophileHUGS at lycos.com
Thu Oct 31 09:16:35 PDT 2013


Daniel Davidson:

> import std.stdio;
> struct RC {
>   this(this) { data = data.dup; }
>   int[] data;
> }
> struct T {
>   const(RC) *rc;
>   void goo() {
>     writeln("Data is ", rc.data);
>   }
> }
>
> T foo() {
>   RC rc = { [1,2,3] };
>   return T(&rc);
> }
>
> void main() {
>   T t = foo();
>   t.goo();
> }

That's wrong code, you are escaping a reference to memory (of rc 
variable) allocated in the stack frame of foo(). The D compiler 
is not smart enough to recognize the bug. There are optimizations 
that patch and avoid this bug (like inlining, or allocating rc 
inside the stack frame of the main) but you can't rely on them.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list