在 C++ 中编写复制构造函数和赋值运算符的清单 [英] Checklist for writing copy constructor and assignment operator in C++

查看:39
本文介绍了在 C++ 中编写复制构造函数和赋值运算符的清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请写出C++中复制构造函数和赋值运算符需要做的任务列表,以保持异常安全,避免内存泄漏等.

解决方案

首先确定你真的需要支持复制.大多数时候情况并非如此,因此禁用两者是可行的方法.

有时,您仍然需要在来自多态层次结构的类上提供复制,在这种情况下:禁用赋值运算符,编写(受保护的?)复制构造函数,并提供虚拟 clone() 函数.

>

否则,如果您正在编写一个值类,您将回到 Coplien 的正交规范形式的领域.如果你有一个不能简单复制的成员,你需要提供一个复制构造函数、一个析构函数、一个赋值运算符和一个默认构造函数.这条规则可以细化,例如参见:The Law of the Big Two>

我还建议您查看 有关赋值运算符的 C++ 常见问题解答copy-and-swap idiomGOTW.

Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc.

解决方案

First be sure you really need to support copy. Most of the time it is not the case, and thus disabling both is the way to go.

Sometimes, you'll still need to provide duplication on a class from a polymorphic hierarchy, in that case: disable the assignment operator, write a (protected?) copy constructor, and provide a virtual clone() function.

Otherwise, in the case you are writing a value class, you're back into the land of the Orthogonal Canonical Form of Coplien. If you have a member that can't be trivially copied, you'll need to provide a copy-constructor, a destructor, an assignment-operator and a default constructor. This rule can be refined, see for instance: The Law of The Big Two

I'd also recommend to have a look at C++ FAQ regarding assignment operators, and at the copy-and-swap idiom and at GOTW.

这篇关于在 C++ 中编写复制构造函数和赋值运算符的清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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