使类不可复制:私有未定义方法与已删除方法 [英] Making a class non-copyable: Private undefined methods vs Deleted methods

查看:77
本文介绍了使类不可复制:私有未定义方法与已删除方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11之前,我看到了这样的代码:

Prior to C++11, I saw code like this:

class Car {
public:
  Car() {}
private:
  Car(const Car&);
  Car& operator=(const Car&);
};

对于C ++ 11(及更高版本),我看到这样的代码:

For C++11 (and later), I see code like this:

class Car {
public:
  Car() {}
private:
  Car(const Car&) = delete;
  Car& operator=(const Car&) = delete;
};

它们的行为相同吗?如果没有,请解释。

Do they behave identically? If not, please explain.

参考: https://ariya.io/2015/01/c-class-and-preventing-object-copy

推荐答案

请注意,您发布的两个摘要给出了完全相同的错误,即:

Note that the two snippets you posted give exactly the same error, that is something like:


在这种情况下, Car(const Car&)是私有的

'Car(const Car&)' is private within this context

这是因为在两种情况下您都将成员方法定义为私有的。

如果您想了解它们之间的区别,则应该公开删除 d d复制构造函数和复制运算符,即:

This is because you defined the member methods as private in both cases.
If you want to appreciate the differences, you should rather have public deleted copy constructor and copy operator, that is:

class Car {
public:
  Car() {}
// private: <-- this should not be here
  Car(const Car&) = delete;
  Car& operator=(const Car&) = delete;
};

通过这种方式,您将被告知这些成员方法已被显式和有意删除

This way, you will be informed that those member methods have been explicitly and intentionally deleted:


使用已删除的功能'Car(const Car&)'

use of deleted function 'Car(const Car&)'

将它们设置为私有并不会明确表示我要删除它们

例如,它可以完成您想强制使用您的类的用户使用工厂方法来创建该类的实例。

Setting them as private doesn't say explicitly I want to delete them.
As an example, it could have been done for you want to force the users of your class to use a factory method to create instances of that class.

无论如何,(不再如此)新功能不是免费的,以非预期的方式使用它们不会带来预期的好处

Anyway, (no longer so) new features are not for free and using them in a way that is not the intended one won't give the expected benefits.

这篇关于使类不可复制:私有未定义方法与已删除方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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