NRVO is a technique invented by Walter Bright around 1991 (the term for it was coined later) to minimize copying of struct data. Functions normally return their function return values in registers. For structs, however, they often are too big to fit in registers. The usual solution to this is to pass to the function ahidden pointer to a struct instance in the caller's stack frame, and the return value is copied there. For example:
struct S {int a, b, c, d; }S foo(){ S result; result.a = 3;return result;}void test(){ S s = foo();}
is rewritten as:
S* foo(S* hidden){ S result; result.a = 3; *hidden = result;return hidden;}void test(){ S tmp; S s = *foo(&tmp);}This rewrite gives us an extra temporary objecttmp, and copies the struct contents twice. What NRVO does is recognize that the sole purpose ofresult is to provide a return value, and so all references toresult can be replaced with*hidden.foo is then rewritten as:
S* foo(S* hidden){ hidden.a = 3;return hidden;}A further optimization is done on the call tofoo to eliminate the other copy, giving:
void test(){ S s; foo(&s);}The result is written directly into the destinations, instead of passing through two other instances.