C++核心準(zhǔn)則C.166:? 重載的單目運算符&只能用于智能指針和引用

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++語義的很多地方為它設(shè)定了默認(rèn)含義。
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.
如果你要"招惹"&運算符,一定要確保它的結(jié)果類型和->,[],*和 . 相匹配。注意 . 運算符現(xiàn)在不能被重載,因此不可能實現(xiàn)完美系統(tǒng)。我們可以希望可以改進這一點:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf。
注意std::addressof()總是返回一個內(nèi)置類型的指針。
Enforcement(實施建議)
Tricky. Warn if?&?is user-defined without also defining?->?for the result type.
不好辦。如果定制了&運算符卻沒有為結(jié)果定義->運算符,報警。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c166-overload-unary--only-as-part-of-a-system-of-smart-pointers-and-references
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
