On Mar 13, 2013 10:12 AM, "Henrik Mannerström" wrote: > > Hello, > > 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 > 5 > > 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? The object in main() already exists when f() is called, so it's address cannot be used as the return address for the function. RVO doesn't work for assignment, only construction. > BR, > Henrik > > > > #include <iostream> > #include <array> > > class MT { > public: > MT(int a = 0) { > data[0] = a; > } > > int val() { > return data[0]; > } > > private: > 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; > } >