C++核心准则C.41:构造函数生成的对象应该被完全初始化

面向对象思考

共 1621字,需浏览 4分钟

 ·

2019-12-27 23:22

f21e33bf6d7120edc6d62e74070b59cd.webp

c741606e05abe1b4717c96b453df8575.webpC.41: A constructor should create a fully initialized object
C.41构造函数生成的对象应该被完全初始化2f87478a812940b318781560f5fa081b.webp


e70b4260542f366af2473f1436659987.webpReason(原因)8268d97dec7a1e509fd23ec3b45d48bd.webp

A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.

构造函数有责任为类建立不变式。类的用户应该可以假设构造出的对象式可用的。


e70b4260542f366af2473f1436659987.webpExample, bad(反面示例)8268d97dec7a1e509fd23ec3b45d48bd.webp
class X1 {
   FILE* f;   // call init() before any other function
   // ...
public:
   X1() {}
   void init();   // initialize f
   void read();   // read from f
   // ...
};

void f()
{
   X1 file;
   file.read();   // crash or bad read!
   // ...
   file.init();   // too late
   // ...
}

Compilers do not read comments.

编译器不会读注释。


e70b4260542f366af2473f1436659987.webpException(例外)8268d97dec7a1e509fd23ec3b45d48bd.webp

If a valid object cannot conveniently be constructed by a constructor, use a factory function.

如果不能方便地通过构造函数构建合法的对象,使用一个工厂函数。


e70b4260542f366af2473f1436659987.webpEnforcement(实施建议)8268d97dec7a1e509fd23ec3b45d48bd.webp
  • (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).

    (简单)所有的构造函数应该初始化所有的成员变量(无论是明确地通过委托构造函数,还是默认构造)

  • (Unknown) If a constructor has an Ensures contract, try to see if it holds as a postcondition.

    (不明)如果构造函数包含Ensures协议,尽量确认是否包含了所有的前置条件。

e70b4260542f366af2473f1436659987.webpNote(注意)8268d97dec7a1e509fd23ec3b45d48bd.webp

If a constructor acquires a resource (to create a valid object), that resource should be released by the destructor. The idiom of having constructors acquire resources and destructors release them is called RAII ("Resource Acquisition Is Initialization").

如果构造函数请求了资源(为了生成合法的对象),那个资源应该被析构函数释放。构造函数申请资源然后析构函数释放它们的做法被称为RAII("资源申请即初始化")。


e70b4260542f366af2473f1436659987.webp原文链接8268d97dec7a1e509fd23ec3b45d48bd.webp

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c40-define-a-constructor-if-a-class-has-an-invariant




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

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

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

浏览 25
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报