洞察纵观鸿蒙next版本,如何凭借FinClip加强小程序的跨平台管理,确保企业在数字化转型中的高效运营和数据安全?
568
2022-11-12
C++核心准则C.133:避免保护型数据成员
C.133: Avoid protected data
C.133:避免保护型数据成员
Reason(原因)
protected data is a source of complexity and errors.protected data complicates the statement of invariants.protected data inherently violates the guidance against putting data in base classes, which usually leads to having to deal with virtual inheritance as well.
保护型数据成员是复杂性和错误的源头。保护型数据使不变式的表现更加复杂。保护数据成员天生违反不要将数据放进基类的原则,这通常也会导致必须同时处理虚继承。
Example, bad(反例)
class Shape { public: // ... interface functions ... protected: // data for use in derived classes: Color fill_color; Color edge_color; Style st; };
Now it is up to every derived Shape to manipulate the protected data correctly. This has been popular, but also a major source of maintenance problems. In a large class hierarchy, the consistent use of protected data is hard to maintain because there can be a lot of code, spread over a lot of classes. The set of classes that can touch that data is open: anyone can derive a new class and start manipulating the protected data. Often, it is not possible to examine the complete set of classes, so any change to the representation of the class becomes infeasible. There is no enforced invariant for the protected data; it is much like a set of global variables. The protected data has de facto become global to a large body of code.
现在每个派生的Shape类都需要正确地处理保护数据。这种做法曾经很流行,但也是维护问题的主要来源。在大规模类层次中,由于代码量很大而且分散在很多类中,因此使用保护数据的一贯性很难维持。可以操作数据的类的集合是开放的:任何人都可以派生出一个新类并操作保护型数据。通常无法完全检查所有这些类,因此对基类表现(数据成员,译者注)的任何修改都变得不可能。不存在针对保护成员的强制性不变量;它们更像一套全局变量。对于大量代码来说,保护类型数据成员事实上已经成为全局的了。
Note(注意)
Protected data often looks tempting to enable arbitrary improvements through derivation. Often, what you get is unprincipled changes and errors.Prefer private data with a well-specified and enforced invariant. Alternative, and often better, keep data out of any class used as an interface.
保护型数据成员经常看起来试图允许通过派生实现自由的改进。通常,你得到的是无规则的修改和错误。更好的选择是包含良好定义的强制不变量的私有数据成员。不将数据放进任何作为接口使用的类中通常也是比较好的选择。
Note(注意)
Protected member function can be just fine.
保护型成员函数问题不大。
Enforcement(实施建议)
Flag classes with protected data.
提示含有保护型数据成员的类。
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c133-avoid-protected-data
觉得本文有帮助?欢迎点赞并分享给更多的人。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~