On Sunday, 27 September 2015 at 13:55:02 UTC, chmike wrote:
Can someone please explain me why this doesn't work as I would expect RVO to work ?

I'm not an expert on the subject so this may contain some inaccuracies, but the gist of it is:

As the name implies, NRVO is an optimization and therefore generally not guaranteed. The compiler is free to use NRVO or not, as it sees fit.

In D there is one case where NRVO is required for correct semantics and therefore guaranteed: returning a struct with disabled postblit. For example:

import std.stdio;
struct S
{
        int i;
        @disable this(this);
}

S foo()
{
        S rv;
        writeln(&rv);
        return rv;
}

void main()
{
        auto s = foo();
        writeln(&s);
}

This will print the same address twice even without optimizations.

If the postblit isn't disabled the compiler will not use NRVO for returning S in this case. Which makes sense, because S is only four bytes, so writing through a pointer will actually be slower. On the other hand if S is large enough, the compiler will switch to using NRVO when possible:

struct S
{
int[16] i; // I just used some large value, didn't test the threshold
}

S foo()
{
        S rv;
        writeln(&rv);
        return rv;
}

void main()
{
        auto s = foo();
        writeln(&s);
}

Reply via email to