前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.23:优先使用{}​初始化器语法

C++核心准则ES.23:优先使用{}​初始化器语法

作者头像
面向对象思考
发布2020-04-28 11:41:44
5380
发布2020-04-28 11:41:44
举报

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

代码语言:javascript
复制
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:

对于容器来讲,习惯上使用{...}表示要素列表,使用()表示大小。

代码语言:javascript
复制
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(示例)
代码语言:javascript
复制
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:

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

代码语言:javascript
复制
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原则某种程度上好一些:

代码语言:javascript
复制
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>

如果你确实想要一个列表初始化,使用={...};

代码语言:javascript
复制
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:

={} 提供拷贝初始化,但是{}提供直接初始化。就像拷贝初始化和直接初始化之间的区别一样,这会使人惊讶。{}接受显式构造函数,={}不会。例如:

代码语言:javascript
复制
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(示例)
代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.23: Prefer the {}-initializer syntax
  • Reason(原因)
    • Exception(例外)
      • Note(注意)
        • Example(示例)
          • Note(注意)
            • Note(注意)
              • Note(注意)
                • Example(示例)
                相关产品与服务
                容器服务
                腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档