find函数常见错误_构造函数中的常见错误

2bd76f6de80261e561ac16855d1dea7e.png

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作为表达函数参数怒的更加普遍的方式。

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


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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值