8

In c++98, the following program is expected to call the copy constructor.

#include <iostream>

using namespace std;
class A
{
  public:
    A() { cout << "default" ; }

    A(int i) { cout << "int" ; }


    A(const A& a) { cout << "copy"; }
};

int main ()
{
   A a1;
   A a2(0);
   A a3 = 0;

  return 0;
}

That is evident if you declare the copy constructor explicit in above case (the compiler errors out). But I don't I see the output of copy constructor when it is not declared as explicit. I guess that is because of copy elision. Is there any way to disable copy elision or does the standard mandates it?

sanjivgupta
  • 396
  • 3
  • 12

2 Answers2

10

Pre C++ 17

A a3 = 0;

will call copy constructor unless copy is elided. Pass -fno-elide-constructors flag

from C++17, copy elision is guaranteed. So you will not see copy constructor getting called.

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
  • Interesting. I was under the impression this would never call a copy constructor, even in `c++11/14`. – super Jun 13 '18 at 10:27
  • No, `A a3 = 0;` [will not](https://wandbox.org/permlink/C8nX13eFdaSmPHAv) call a copy constructor in pre-C++17 standards on GCC. The reason it does is because you included the flag in your compilation string. – Ron Jun 13 '18 at 10:35
  • @Ron I thought so too, but what about [this](https://wandbox.org/permlink/4wQT166R2jVFw4pb)? – super Jun 13 '18 at 10:40
  • @Ron What if `A a3 = 0;` is `A a3 = A(0);` – Gaurav Sehgal Jun 13 '18 at 10:49
0

You have wrong understanding what the copy elision is. Please refer to this question for more info.

In this particular case, if you define the constructor explicit, it will cause an error because A a3 = 0; on this line the compiler created a object using 0.

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76