问题描述
在c ++ 98中,预期以下程序将调用复制构造函数。
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?
推荐答案
Pre C ++ 17
A a3 = 0;
将副本构造函数。从 C ++ 17 $>传递
-fno-elide-constructors
标志
will call copy constructor unless copy is elided. Pass -fno-elide-constructors
flag
c $ c>,可以保证复制省略。因此,您将复制构造函数被调用。
from C++17
, copy elision is guaranteed. So you will not see copy constructor getting called.
这篇关于有没有办法在C ++编译器中禁用复制省略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!