Copy misunderstanding Elision

#include <iostream> struct A { A() { std::cout << "Def Constr\n"; } A(const A&) { std::cout << "Copy Constr\n"; } }; A func1() { return A{}; } void func2(A a) {} int main() { func2(func1()); } 

After compiling with

g ++ Copy.cpp -std = C ++ 11 -fno-elide-constructors

Exit:

Def constr

Copy Constr

Copy Constr

And my questions: why 2 Copy Constr? I thought that only 1 copy is required.

Perhaps I have an assumption that func1 () throws a temporary object, and this temp object needs to be copied to another memory area and from this region again make a copy for the func2 () parameter, but this is uncertain for me.

Could you explain this in detail?

+7
c ++ c ++ 11 copy-elision
source share
2 answers

Yes, your understanding is correct. Your line of code (without copying) is like

 int main() { { A temp = func1(); // 2nd copy func2(temp); // 3rd copy } } 
+2
source share
  • The return value of func1 copied from the expression A{} .
  • The value of the func1() function expression is copied to the func2 function func2 .
+6
source share

All Articles