How to Disable Copy Elision in C++ Compiler

c++copy-constructorinitialization

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?

Best Answer

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.