18 October 2022

C++ 核心指南目录

“Prefer initialization to assignment in constructors”

理由

所谓初始化,就是要进行初始化,而不是赋值。初始化操作更优雅,效率更高。可以防止设置之前使用(use before set)之类的错误。

好例子

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

坏例子

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
    // ...
};

更好地例子

这里我们不用 const char* s 我们用 C++17 中的 std::string_viewgsl::span<char> 做函数的参数:

class D {   // Good
    string s1;
public:
    D(string_view v) : s1{v} { }    // GOOD: directly construct
    // ...
};