减少 operator= 和复制构造函数之间的代码重复 [英] Reducing code duplication between operator= and the copy constructor

查看:34
本文介绍了减少 operator= 和复制构造函数之间的代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要非默认复制构造函数和赋值运算符的类(它包含指针列表).有没有什么通用的方法可以减少复制构造函数和赋值运算符之间的代码重复?

I have a class that requires a non-default copy constructor and assignment operator (it contains lists of pointers). Is there any general way to reduce the code duplication between the copy constructor and the assignment operator?

推荐答案

没有通用方法"可以编写适用于所有情况的自定义复制构造函数和赋值运算符.但是有一个成语叫做copy-&-swap":

There's no "general way" for writing custom copy constructors and assignment operators that works in all cases. But there's an idiom called "copy-&-swap":

 class myclass
 {
    ...
 public:
    myclass(myclass const&);

    void swap(myclass & with);

    myclass& operator=(myclass copy) {
        this->swap(copy);
        return *this;
    }

    ...
};

它在许多(但不是所有)情况下都很有用.有时你可以做得更好.向量或字符串可以有更好的分配,如果足够大,可以重用分配的存储.

It's useful in many (but not all) situations. Sometimes you can do better. A vector or a string could have a better assignment which reuses allocated storage if it was large enough.

这篇关于减少 operator= 和复制构造函数之间的代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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