前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.166:​ 重载的单目运算符&只能用于智能指针和引用

C++核心准则C.166:​ 重载的单目运算符&只能用于智能指针和引用

作者头像
面向对象思考
发布2020-03-25 16:59:19
4500
发布2020-03-25 16:59:19
举报

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(示例)

代码语言:javascript
复制
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


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C.166: Overload unary & only as part of a system of smart pointers and references
  • Reason(原因)
    • Note(注意)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档