Why does not RVO work in this case?

Henrik Mannerström henrik.mannerstrom@gmail.com
Wed Mar 13 10:11:00 GMT 2013


Below is my trivial test case that I think should exhibit return value
optimization. However, when I run it I get the following result:
Address of a in main    0x7fff676bb130
Address of a in func    0x7fff676ba190

I compiled with:
g++ -std=gnu++0x -Wall -Wextra -pedantic -O2 test1.cc

My compiler is:
> g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.

I guess the return values are not optimized away. How should I enable RVO?


#include <iostream>
#include <array>

class MT {
  MT(int a = 0) {
    data[0] = a;

  int val() {
    return data[0];

  std::array<int, 1000> data;

MT func() {
  MT a(5);
  std::cout << "Address of a in func\t" << &a << std::endl;
  return a;

int main() {
  MT a;
  std::cout << "Address of a in main\t" << &a << std::endl;
  a = func();
  std::cout << a.val() << std::endl;
  return 0;

More information about the Gcc-help mailing list