C++会在哪些场合自动生成默认的拷贝构造/拷贝赋值函数?

不考虑default关键字一定生成的场合.
我问gpt得到的回复是,比方说,在没有拷贝构造函数的情况下.
"没有显式定义移动构造函数,移动赋值函数,析构函数"的情况下会自动生成.

这是测试用的类.

class Base
{
    public:
        int x;
        Base():x(0){
            cout<<"default constru"<<endl;
        }
        Base(int x):x(x){
            cout<<"constru"<<endl;
        }
};

这是测试用的代码.

int main()
{
    Base b1{1};
    Base b2{b1};//调用拷贝构造.
    b1=b2;//调用拷贝赋值
    return 0;
}

但,我经过测试,发现,只给Base类添加移动构造/移动赋值函数的定义的话,它确实不会自己生成拷贝构造函数了.
但如果添加定义析构函数的显式定义的话,它实际上是会生成一个默认拷贝构造函数的.
这是怎么回事呢?

阅读 187
1 个回答

有自定义析构函数情况,现阶段会生成拷贝构造。

但是这一行为已经在标准中被标记为 deprecated (在现阶段的 c++26 draft 中依然如此),可能在未来就会规定为 deleted 。

https://timsong-cpp.github.io/cppwp/n4868/class.copy.ctor#6

If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly.
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted ([dcl.fct.def]).
The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor ([depr.impldec]).

https://timsong-cpp.github.io/cppwp/n4868/class.copy.assign#2

If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly.
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy assignment operator is defined as deleted; otherwise, it is defined as defaulted ([dcl.fct.def]).
The latter case is deprecated if the class has a user-declared copy constructor or a user-declared destructor ([depr.impldec]).
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏