Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to disable copy elision in c++ compiler

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?

like image 844
sanjivgupta Avatar asked Jun 13 '18 09:06

sanjivgupta


1 Answers

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.

like image 122
Gaurav Sehgal Avatar answered Nov 15 '22 13:11

Gaurav Sehgal