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

避免重复实现由默认拷贝、移动、析构函数完成的功能

5.1.10 ID_violateRuleOfZero
目录 › next › previous

当类只负责成员对象的包装或组合而没有特殊的复制、移动、析构需求时,不应定义下列函数:

  1. 拷贝构造函数
  2. 拷贝赋值运算符
  3. 析构函数
  4. 移动构造函数
  5. 移动赋值运算符

应由编译器生成相关默认函数,否则会产生多余的代码,增加维护成本,这种规则称为“Rule of zero”。

示例:

class A {
    string a, b;

public:
    A(const A& rhs): a(rhs.a), b(rhs.b) {  // Redundant
    }
    A& operator = (const A& rhs) {  // Redundant
        a = rhs.a;
        b = rhs.b;
        return *this;
    }
   ~A() {  // Redundant
    }
};

例中的类只涉及字符串对象的组合,复制、移动和析构可交由成员对象完成,其拷贝构造函数、赋值运算符以及析构函数是多余的,应该去掉,编译器会进行更好地处理。

相关

ID_violateRuleOfFive

参考

C++ Core Guidelines C.21
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.