前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.49:构造函数中应该做的是初始化而不是赋值

C++核心准则C.49:构造函数中应该做的是初始化而不是赋值

作者头像
面向对象思考
发布2020-03-25 16:13:17
1.2K0
发布2020-03-25 16:13:17
举报

C.49: Prefer initialization to assignment in constructors C.49:构造函数中应该做的是初始化而不是赋值

Reason(原因)

An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.

初始化明确地表明所做的是初始化而不是赋值,而且可以做得更优美,更有效率。防止“赋值之前使用”的错误。

Example, good(良好示例)

代码语言:javascript
复制
class A {   // Good
    string s1;
public:
    A(czstring p) : s1{p} { }    // GOOD: directly construct (and the C-string is explicitly named)
    // ...
};

Example, bad(反面示例)

代码语言:javascript
复制
class B {   // BAD
    string s1;
public:
    B(const char* p) { s1 = p; }   // BAD: default constructor followed by assignment
    // ...
};

class C {   // UGLY, aka very bad
    int* p;
public:
    C() { cout << *p; p = new int{10}; }   // accidental use before initialized
    // ...
};

Example, better still(更好的示例)

Instead of those const char*s we could use gsl::string_span or (in C++17) std::string_view as a more general way to present arguments to a function:

相对于那些const char* s,我们应该可以使用gsl::string_span或者(C++17引入的)std::string_view作为表达函数参数怒的更加普遍的方式(https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rstr-view)。

代码语言:javascript
复制
class D {   // Good
    string s1;
public:
    A(string_view v) : s1{v} { }    // GOOD: directly construct
    // ...
};

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c49-prefer-initialization-to-assignment-in-constructors


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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档