重载赋值运算符不返回“this”¶
ID: cpp/assignment-does-not-return-this
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- reliability
- readability
- language-features
- external/jsf
Query suites:
- cpp-security-and-quality.qls
此规则查找未返回对 this
的引用的赋值运算符定义。需要对 this
的引用,以便赋值表达式具有有意义的值(即,使像 a = b = 3
这样的表达式能够正确地工作)。不返回对 this
的引用将使赋值表达式具有意外的值,这很可能会导致此类链式赋值失败。标准库类型和内置类型都具有这种行为,而且赋值运算符的默认行为几乎是所有开发人员的普遍假设,因此不建议大幅度改变它。如果所需的行为与默认赋值运算符的行为有很大差异,最好定义一个单独的函数。
建议¶
确保赋值运算符重载返回对 this
的引用。如果所需赋值运算符与默认行为有很大差异,请定义一个单独的函数。
示例¶
class B {
B& operator=(const B& other) {
... //incorrect, does not return a reference to this
}
};
class C {
C& operator=(const C& other) {
...
return *this; //correct, returns reference to this
}
};
参考资料¶
AV 规则 82,《联合攻击战斗机空中载具 C++ 编码标准》。洛克希德·马丁公司,2005 年。
S. Meyers。《Effective C++ 第 3 版》。第 52-53 页。Addison-Wesley Professional,2005 年。