On 12/7/09, Rodolfo Federico Gamarra <rgamarra@xxxxxxxxx> wrote: > Hi all, > > I have been reviewing the RVO optimization technique and came across > with a nested function call where I hoped this optmization to work as > well. > I compiled the following snippet with > g++ -O3 main.cc -o main > and got as result > A() > N() > A(A&) > > Is there any fundamental reason for this optimization not to happen in > this case? I was hoping to get only one object constructed at all. The > relevant passage in the standard seems to me is "12.8 - Copying class > objects (15)". > // main.cc > #include <iostream> > using namespace std; > struct A { > A() { cout << "A()\n"; } > A(const A& a) { cout << "A(const A&)\n"; } > A(A& a) { cout << "A(A&)\n"; } > A& operator=(const A& a) { cout << "operator=(const A&)\n"; } > void N() { cout << "N()\n"; } > }; > A AlternativeA(A a) { a.N(); return a; } > A FactoryA() { return A(); } > int main() { A a = AlternativeA(FactoryA()); } > //eof > > Thanks a lot for your help in advance. The function AlternativeA does not construct "a", and hence one could argue that RVO does not apply. Conversely, one could argue that the standard's rule doesn't talk about function boundaries wrt the construction of the automatic object, and hence RVO does apply. That latter interpretation is somewhat inconsistent with the structure of compilers, and of GCC in particular, because inlining happens after RVO. To change the current behavior, you would need a convincing case that the performance benefit is significant. -- Lawrence Crowl