C++核心准则C.49:构造函数中应该做的是初始化而不是赋值
发布日期:2021-07-01 05:26:35 浏览次数:3 分类:技术文章

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

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

 

class A {   // Good    string s1;public:    A(czstring p) : s1{p} { }    // GOOD: directly construct (and the C-string is explicitly named)    // ...};

 

 

Example, bad(反面示例)

 

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)。

 

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

 


 

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

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

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

上一篇:C++核心准则C.50:如果在构造过程中需要“虚行为”,使用工厂函数
下一篇:C++核心准则C.48:如果构造函数需要用常数初始化成员,使用类内初始化器更合适

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月15日 00时52分18秒