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

2

9

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?

Ramose answered 13/6, 2018 at 9:50 Comment(4)
Where should the copy constructor be called?Till
I see no usage of copy construction in the main function.Polio
gcc have -fno-elide-constructors to disable copy elisionBlanketyblank
Clang has this flag too.Farny
I
13

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.

Ibadan answered 13/6, 2018 at 10:12 Comment(4)
Interesting. I was under the impression this would never call a copy constructor, even in c++11/14.Potable
No, A a3 = 0; will not 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.Halvorson
@Halvorson I thought so too, but what about this?Potable
@Halvorson What if A a3 = 0; is A a3 = A(0);Ibadan
D
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.

Dulci answered 13/6, 2018 at 9:56 Comment(2)
constructor being explicit has nothing to do with copy elision.Wheelwright
I agree his understanding is wrong (via comments), but he has got the answer correct.Wheelwright

© 2022 - 2024 — McMap. All rights reserved.