C++核心准则C.166: 重载的单目运算符&只能用于智能指针和引用
共 1428字,需浏览 3分钟
·
2020-03-03 23:22
C.166: Overload unary & only as part of a system of smart pointers and references
C.166: 重载的单目运算符&只能用于智能指针和引用
Reason(原因)
The & operator is fundamental in C++. Many parts of the C++ semantics assumes its default meaning.
取地址运算符&是C++的基本要素,C++语义的很多地方为它设定了默认含义。
Example(示例)
class Ptr { // a somewhat smart pointer
Ptr(X* pp) :p(pp) { /* check */ }
X* operator->() { /* check */ return p; }
X operator[](int i);
X operator*();
private:
T* p;
};
class X {
Ptr operator&() { return Ptr{this}; }
// ...
};
Note(注意)
If you "mess with" operator & be sure that its definition has matching meanings for ->, [], *, and . on the result type. Note that operator . currently cannot be overloaded so a perfect system is impossible. We hope to remedy that: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf. Note that std::addressof() always yields a built-in pointer.
如果你要"招惹"&运算符,一定要确保它的结果类型和->,[],*和 . 相匹配。注意 . 运算符现在不能被重载,因此不可能实现完美系统。我们可以希望可以改进这一点:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf。
注意std::addressof()总是返回一个内置类型的指针。
Enforcement(实施建议)
Tricky. Warn if & is user-defined without also defining -> for the result type.
不好办。如果定制了&运算符却没有为结果定义->运算符,报警。
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c166-overload-unary--only-as-part-of-a-system-of-smart-pointers-and-references
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!