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

拈花ヽ惹草 提交于 2020-01-13 17:57:18

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/50834215/is-there-a-way-to-disable-copy-elision-in-c-compiler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!