☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

拷贝赋值运算符应处理参数是自身对象时的情况

8.20 ID_this_selfJudgement
目录 › next › previous

如果拷贝赋值运算符的参数是自身对象,需防止资源分配和回收方面的冲突。

示例:

class A { .... };

void foo(A* p, A* q) {
    *p = *q;             // If ‘p’ and ‘q’ point to the same object ...
}

设例中 A 是需要深拷贝的类,其赋值运算符往往需要先释放自身的资源,再复制参数的资源,如果参数就是自身,则需要避免资源被释放,可在赋值运算符中判断 this 与参数地址是否相同:

A& A::operator = (const A& rhs) {
    if (this != &rhs) {             // Required
        ....
    }
    return *this;
}

如果 A 的拷贝构造函数和交换方法齐备,也可按“复制 - 交换”模式实现:

A& A::operator = (const A& rhs) {
    A tmp(rhs);
    this->swap(tmp);                // Good
    return *this;
}

利用创建临时对象并与之交换的方法,也有效规避了冲突,这种方法使各函数更专注于自己的职责,不必重复编写分配和回收相关的代码,建议采用这种方法。

参考

C++ Core Guidelines C.62 SEI CERT OOP54-CPP
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.