C ++ 11中3个默认成员弃用的规则 [英] Rule of 3 Default Member Deprecation in C++11

查看:42
本文介绍了C ++ 11中3个默认成员弃用的规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据以下广为人知的表,当用户提供一个或多个副本分配,副本构造函数和析构函数中的一个或多个时,不赞成在C ++ 11中自动生成默认副本构造函数和副本分配的编译器.(红色单元格表示已弃用).鉴于"3规则",这是完全合理的.但是,该表显示,在用户提供的副本构造函数/赋值的情况下,不建议使用默认析构函数的生成.

According to the below widely-known table, automatic compiler generation of default copy constructor and copy assignment is deprecated in C++11 when one or more of the copy assignment, copy constructor, and destructor is/are supplied by the user (the red cells indicate deprecation). This makes perfect sense in light of the "Rule of 3". However, the table shows that generation of the default destructor is not deprecated in the case of user-supplied copy constructor/assignment.

此设计决定的依据是什么?

What is the rationale behind this design decision?

推荐答案

为什么不建议使用它?一个对象完全有可能需要特殊的复制属性,但是其销毁完全取决于其子对象析构函数.考虑一个简单的克隆指针:

Why should it be deprecated? It's perfectly possible for an object to require special copying properties, but its for destruction to be fully determined by its sub-object destructors. Consider a simple cloning pointer:

template <class T>
class cloning_ptr
{
  std::unique_ptr<T> p;

public:
  cloning_ptr(const cloning_ptr &src) : p(std::make_unique<T>(*src.p) {}
  cloning_ptr(cloning_ptr &&) = default;

  cloning_ptr& operator= (cloning_ptr rhs)
  { swap(p, rhs.p); return *this; }    
};

没有任何理由提供一个析构函数,该析构函数执行与默认变量不同的任何操作.

There's zero reason to provide a destructor that does anything different from the defaulted one.

另一种方法是不同的:如果您需要在dtor中执行特殊操作,则可能意味着该类中存在一些非标准所有权模型.非标准所有权也很可能也需要在复制操作中处理.

The other way around is different: if you need to do special things in a dtor, that probably means there is some non-standard ownership modeled in the class. Non-standard ownership will most likely need handling in copy operations, too.

这篇关于C ++ 11中3个默认成员弃用的规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆