Copy Elision Misunderstanding
Asked Answered
M

2

7
#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

Output is :

Def Constr

Copy Constr

Copy Constr

And my questions is : Why 2 Copy Constr ? I thought only 1 Copy was needed.

I might have a guess that func1() throws a temp object and this temp object needs to be copied to another memory region and from that region again a copy must be made for the func2() parameter but it's vague for me .

Could you explain it in detail please ?

Morphogenesis answered 6/3, 2015 at 12:31 Comment(1)
I wonder how the result will be different if func2 takes const reference.Paulino
P
2

Yes your understanding is right. Your line of code (without copy eliding) is similar to

int main()
{
  {
    A temp = func1();  // 2nd copy
    func2(temp);  // 3rd copy
  }
}
Philous answered 6/3, 2015 at 12:37 Comment(0)
N
6
  1. The return value of func1 is copied from the expression A{}.
  2. The value of the function call expression func1() is copied into the function parameter of func2.
Nereidanereids answered 6/3, 2015 at 12:33 Comment(0)
P
2

Yes your understanding is right. Your line of code (without copy eliding) is similar to

int main()
{
  {
    A temp = func1();  // 2nd copy
    func2(temp);  // 3rd copy
  }
}
Philous answered 6/3, 2015 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.