C++核心準則ES.23:優先使用{} 初始化器語法

ES.23: Prefer the {}-initializer syntax

ES.23:優先使用{}初始化器語法

 

Reason(原因)

Prefer {}. The rules for {} initialization are simpler, more general, less ambiguous, and safer than for other forms of initialization.

優先使用{}。{}初始化器原則簡單,更通用,更少歧義,並且比其他形式的初始化更安全。

Use = only when you are sure that there can be no narrowing conversions. For built-in arithmetic types, use = only with auto.

Avoid () initialization, which allows parsing ambiguities.

只在你確定不會發生窄化時使用=。對於內置算數類型,只在給auto賦值時使用=。避免()初始化,它允許模糊解析.

 

Example(示例)

int x {f(99)};
int y = x;
vector<int> v = {1, 2, 3, 4, 5, 6};

Exception(例外)

For containers, there is a tradition for using {...} for a list of elements and (...) for sizes:

對於容器來講,習慣上使用{...}表示要素列表,使用()表示大小。

vector<int> v1(10);    // vector of 10 elements with the default value 0
vector<int> v2{10};    // vector of 1 element with the value 10

vector<int> v3(1, 2);  // vector of 1 element with the value 2
vector<int> v4{1, 2};  // vector of 2 element with the values 1 and 2

Note(注意)

{}-initializers do not allow narrowing conversions (and that is usually a good thing) and allow explicit constructors (which is fine, we're intentionally initializing a new variable).

{}初始化器不允許窄化轉換(這通常是好事)並且允許顯式構造函數(這沒有問題,我們就是要初始化一個新變量)

 

Example(示例)

int x {7.9};   // error: narrowing
int y = 7.9;   // OK: y becomes 7. Hope for a compiler warning
int z = gsl::narrow_cast<int>(7.9);  // OK: you asked for it

Note(注意)

{} initialization can be used for nearly all initialization; other forms of initialization can't:

{}初始化器差不多可以被用於任何初始化;其他形式的初始化則不行。

auto p = new vector<int> {1, 2, 3, 4, 5};   // initialized vector
D::D(int a, int b) :m{a, b} {   // member initializer (e.g., m might be a pair)
    // ...
};
X var {};   // initialize var to be empty
struct S {
    int m {7};   // default initializer for a member
    // ...
};

For that reason, {}-initialization is often called "uniform initialization" (though there unfortunately are a few irregularities left).

由於這個原因,{}初始化經常被稱爲“統一初始化”(雖然很不幸還存在很少的例外。)

 

Note(注意)

Initialization of a variable declared using auto with a single value, e.g., {v}, had surprising results until C++17. The C++17 rules are somewhat less surprising:

用一個單值初始化一個用auto聲明的變量,例如:{v},在C++17之前會產生以外的結果,C++17原則某種程度上好一些:

auto x1 {7};        // x1 is an int with the value 7
auto x2 = {7};      // x2 is an initializer_list<int> with an element 7

auto x11 {7, 8};    // error: two initializers
auto x22 = {7, 8};  // x22 is an initializer_list<int> with elements 7 and 8

Use ={...} if you really want an initializer_list<T>

如果你確實想要一個列表初始化,使用={...};

auto fib10 = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};   // fib10 is a list

Note(注意)

={} gives copy initialization whereas {} gives direct initialization. Like the distinction between copy-initialization and direct-initialization itself, this can lead to surprises. {} accepts explicit constructors; ={} does not. For example:

={} 提供拷貝初始化,但是{}提供直接初始化。就像拷貝初始化和直接初始化之間的區別一樣,這會使人驚訝。{}接受顯式構造函數,={}不會。例如:

struct Z { explicit Z() {} };

Z z1{};     // OK: direct initialization, so we use explicit constructor
Z z2 = {};  // error: copy initialization, so we cannot use the explicit constructor

Use plain {}-initialization unless you specifically want to disable explicit constructors.

使用直接的{}初始化,除非你就是想禁止顯式構造函數。

 

Example(示例)

template<typename T>
void f()
{
    T x1(1);    // T initialized with 1
    T x0();     // bad: function declaration (often a mistake)

    T y1 {1};   // T initialized with 1
    T y0 {};    // default initialized T
    // ...
}

See also: Discussion

參見:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#???

 

Enforcement(實施建議)

  • Flag uses of = to initialize arithmetic types where narrowing occurs.

  • 提示使用=進行算數類型的初始化而且發生窄化轉換的情況。

  • Flag uses of () initialization syntax that are actually declarations. (Many compilers should warn on this already.)

  • 提示使用()初始化語法但實際上是聲明的情況(很多編譯器應該已經對這種情況報警)

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es23-prefer-the--initializer-syntax

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章