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

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

问题描述

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

解决方案

首先确保你真的需要支持复制。



有时候,你仍然需要从一个类中提供重复多态层次结构,在这种情况下:禁用赋值运算符,写一个(protected?)复制构造函数,并提供一个虚拟clone()函数。

你正在写一个价值类,你回到了Coplien的正交规范形式的土地。如果你有一个不能被简单复制的成员,你需要提供一个复制构造函数,析构函数,赋值运算符和默认构造函数。此规则可以细化,例如: The Big Two



我还建议您查看 C ++常见问题关于赋值运算符,以及在复制和交换惯用语 GOTW


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天全站免登陆