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(示例)
Exception(例外)
For containers, there is a tradition for using {...} for a list of elements and (...) for sizes:
对于容器来讲,习惯上使用{...}表示要素列表,使用()表示大小。
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(示例)
Note(注意)
{} initialization can be used for nearly all initialization; other forms of initialization can't:
{}初始化器差不多可以被用于任何初始化;其他形式的初始化则不行。
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原则某种程度上好一些:
Use ={...} if you really want an initializer_list<T>
如果你确实想要一个列表初始化,使用={...};
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:
={} 提供拷贝初始化,但是{}提供直接初始化。就像拷贝初始化和直接初始化之间的区别一样,这会使人惊讶。{}接受显式构造函数,={}不会。例如:
Use plain {}-initialization unless you specifically want to disable explicit constructors.
使用直接的{}初始化,除非你就是想禁止显式构造函数。
Example(示例)
See also: Discussion
参见:
https:///isocpp/CppCoreGuidelines/blob/master/#???
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:///isocpp/CppCoreGuidelines/blob/master/#es23-prefer-the--initializer-syntax
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】
















