gpt4 book ai didi

c++ - 如果类包含用户声明的析构函数,那么复制构造函数有什么用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:25 31 4
gpt4 key购买 nike

第 12.8/7 节中的标准说:

If the class definition does not explicitly declare a copy constructor, 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 (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor. Thus, for the class definition

struct X {
X(const X&, int);
};

a copy constructor is implicitly-declared. If the user-declared constructor is later defined as

X::X(const X& x, int i =0) { /∗ ... ∗/ }

我不明白那个意思如果类具有用户声明的复制赋值运算符或用户声明的析构函数,则不推荐使用后一种情况。在示例中,标准既不提供用户声明的复制赋值运算符或析构函数。如果我们声明一个析构函数或一个复制赋值运算符会发生什么?我尝试按如下方式进行:

struct A
{
~A(){ };
};

A::A(const A&){ }; //error

int main(){ }

DEMO

但在示例中我们仍然有隐式声明的复制构造函数。该规则的实际含义是什么?

我想如果我们写成下面这样:

struct A
{
A(){ };
A(const A&&){ };
~A(){ };
};

A a;

A t = a; //error: call to implicitly-deleted copy constructor of 'A'

int main()
{

}

DEMO

复制构造函数不会显式删除。但事实并非如此。

最佳答案

这个弃用基本上包含了三(五)规则。如果提供了用户声明的复制赋值运算符或析构函数,则复制构造函数被定义为默认(而不是已删除)的事实将被弃用。这应该可以防止您将来依赖这种隐式声明的复制构造函数。

In the example the Standard provides neither copy assignment nor destructor are user-decalred.

该示例与弃用无关。

I've tryied to do that as follows: […] but in the example we still have the impliclty-declared copy constructor.

您不能定义隐式声明的复制构造函数 - 因为它已经被 = default 定义(没有双关语意)。您必须先自行声明。

I thought that If we wirte the following: […] the copy-constructor won't explicitly deleted. But it's not true.

引用了明确指定如果声明了移动构造函数,复制构造函数将被隐式定义为已删除的规则:

If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted;

显然,

A(const A&&){ }

是根据 [class.copy]/3 的移动构造函数。如果您删除了此移动构造函数,则 your example compiles ,尽管它使用了上述已弃用的功能。

关于c++ - 如果类包含用户声明的析构函数,那么复制构造函数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26687426/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com