C++核心准则ES.63:不要分割处理对象
发布日期:2021-07-01 05:28:18 浏览次数:2 分类:技术文章

本文共 2004 字,大约阅读时间需要 6 分钟。

ES.63: Don't slice

ES.63:不要分割处理对象

 

Reason(原因)

Slicing -- that is, copying only part of an object using assignment or initialization -- most often leads to errors because the object was meant to be considered as a whole. In the rare cases where the slicing was deliberate the code can be surprising.

分割指的是在赋值或初始化对象是只处理对象一部分--多数情况下会导致错误,因为对象本来希望作为一个整体被处理。极少情况下确实需要分割处理,但是这样的代码会很难理解。

 

Example(示例)

class Shape { /* ... */ };class Circle : public Shape { /* ... */ Point c; int r; };Circle c {
{0, 0}, 42};Shape s {c}; // copy construct only the Shape part of Circles = c; // or copy assign only the Shape part of Circlevoid assign(const Shape& src, Shape& dest) { dest = src;}Circle c2 {
{1, 1}, 43};assign(c, c2); // oops, not the whole state is transferredassert(c == c2); // if we supply copying, we should also provide comparison, // but this will likely return false

The result will be meaningless because the center and radius will not be copied from c into s. The first defense against this is to define the base class Shape not to allow this.

由于中心和半径不会从c复制给s,因此产生没有意义的结果。第一种保护措施禁止基类的赋值操作。

 

Alternative(可选项)

If you mean to slice, define an explicit operation to do so. This saves readers from confusion. For example:

如果确实需要分割处理对象,定义一个显式操作完成这个功能。这样可以避免读者困惑。例如:

class Smiley : public Circle {    public:    Circle copy_circle();    // ...};Smiley sm { /* ... */ };Circle c1 {sm};  // ideally prevented by the definition of CircleCircle c2 {sm.copy_circle()};

Enforcement(实施建议)

Warn against slicing.

发现分割处理发出警告。

 

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es63-dont-slice

 


新书介绍

以下是本人3月份出版的新书,拜托多多关注!

 

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

转载地址:https://oothinking.blog.csdn.net/article/details/107384778 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:在Ubuntu20.04环境中构建C++20开发环境(GCC11)
下一篇:C++核心准则ES.62:不要比较不同数组中的元素地址

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月21日 00时25分57秒