C ++中的三元规则 [英] Rule of Three in C++

查看:235
本文介绍了C ++中的三元规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读三项规则,什么是三项规则? 总结如下:

I've read that The Rule of Three, What is The Rule of Three? is summarized as follows:


如果您需要显式声明析构函数,复制构造函数或复制赋值
运算符自己,你可能需要显式声明所有这三个。

If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

我的问题是:在C ++应用程序中,我有一个管理资源的类(具有处理删除指针的析构函数)。我知道应用程序使用赋值运算符在所有的地方,但我绝对确定在应用程序中没有使用复制构造函数,即使用类型类c(..);类d(c); 所以在这些情况下,我仍然需要实现一个赋值运算符和一个复制构造函数?或者一个赋值运算符本身就足够了?是否可能赋值运算符以某种方式使用复制构造函数?

My question is: In a C++ application, I have a class that manages resources (has a destructor that handles deleting pointers). I know that the application uses assignment operator all over the place, but I am absolutely certain that there is no usage in the application of a copy constructor, i.e., usage of the type Class c(..); Class d(c); so under these circumstances, am I still required to implement both an assignment operator and a copy constructor? Or will an assignment operator alone suffice? Is it possible that the assignment operator uses the copy constructor somehow?

感谢您的想法。

推荐答案

如果您知道复制构造函数不会被使用,您可以通过将其设为private和未实现来表示:

If you know that the copy constructor won't be used, you can express that by making it private and unimplemented, thus:

class C
{
private:
    C(const C&); // not implemented
};

(在C ++ 11中可以使用新的 = delete 语法)。也就是说,你应该这样做,如果你绝对确定它永远不会需要。否则,你可能会更好地实现它。重要的是不要只是离开它,因为在这种情况下,编译器将提供一个默认的成员复制构造函数,将做错了的事情 - 这是一个问题等待发生。

(in C++11 you can use the new = delete syntax). That said, you should only do that if you're absolutely sure it will never be needed. Otherwise, you might be better off implementing it. It's important not to just leave it as is, as in that case the compiler will provide a default memberwise copy constructor that will do the wrong thing - it's a problem waiting to happen.

在某种程度上,它取决于类将被用于 - 如果你正在写一个类是库的一部分,例如,为了一致性原因实现复制构造函数更有意义。你不知道你的课程将如何使用。

To some extent it depends on what the class is going to be used for - if you're writing a class that's part of a library, for instance, it makes much more sense to implement the copy constructor for consistency reasons. You have no idea a priori how your class is going to be used.

这篇关于C ++中的三元规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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