2011-10-06

Named return value optimization in gcc

This blog post demonstrates that GCC 4.1 does Named return value optimization, i.e. it omits creating a temporary object in a function returning an object if all return statements in the function return the same local variable. Example code:

#include <stdio.h>

class C {
 public:
  C() { printf("+\n"); }
  ~C() { printf("-\n"); }
  C(const C&) { printf(":\n"); }
  C& operator=(const C&) { printf("=\n"); }
};

C F(int i) {
  C x;
  if (i > 1) {
    return x;
  } else {
    return x;
  }
}

C G(int i) {
  if (i > 1) {
    C x;
    return x;
  } else {
    C y;
    return y;
  }
}

int main(int argc, char**) {
  F(argc);
  printf("~~~\n");
  G(argc);
  return 0;
}

The output, as expected, even without -O... compiler optimization flags:

$ g++ test_return_object.cc && ./a.out
+
-
~~~
+
:
-
-

1 comment:

Unknown said...

Nice article. Is there a good citation/reference for the fact that the named variable should be the same for the trigger to RVO?