Rvalue references - The resolution

Maxim Fomin maxim at maxim-fomin.ru
Thu May 9 13:50:16 PDT 2013


On Saturday, 4 May 2013 at 18:33:04 UTC, Walter Bright wrote:
> Thanks to the many recent threads on this, and the dips on it, 
> everyone was pretty much up to speed and ready to find a 
> resolution. This resolution only deals with the memory safety 
> issue.

...

What if an argument is captured by a delegate?

import std.stdio;

alias long[100] T;

T delegate() dg;

//ref T foo(ref T i) @safe
void foo(ref T i) @safe
{
    dg = { return i; } ;
    //return i;
}

//ref T bar()
void bar() @safe
{
    T i = 1;
    //return foo(i);
    foo(i);
}

void rewrite_stack() @safe
{
    T tmp = -1;
}

void main()
{
    //T i = bar();
    bar();
    rewrite_stack();
    writeln(dg());
}

I believe that even taking your runtime solution into account 
there is still flaw in the code which is caused by capturing 
reference (pointer) to passed object. Since definition of 'foo' 
may be unavailable, compiler cannot know during issuing call to 
'bar' whether to allocate argument on the stack or in the heap.

By the way, lazy+delegate is broken.

auto foo(lazy int i) @safe
{
    return { return i; } ;
}

auto bar() @safe
{
    int i = 4;
    return foo(i);
}

void baz() @safe
{
    int[1] arr = 2;
}

void main() @safe
{
    auto x = bar();
    baz();
    assert(x() is 2); // stack value hijacktion
}

First example: http://dpaste.dzfl.pl/4c84a5e4
Second example: http://dpaste.dzfl.pl/9399adc6


More information about the Digitalmars-d mailing list