C++怎么使用{}​初始化器语法

发布时间:2021-11-26 14:40:30 作者:iii
来源:亿速云 阅读:177

本篇内容介绍了“C++怎么使用{}初始化器语法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

ES.23:优先使用{}初始化器语法

Reason(原因)

优先使用{}。{}初始化器原则简单,更通用,更少歧义,并且比其他形式的初始化更安全。

只在你确定不会发生窄化时使用=。对于内置算数类型,只在给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(注意)

{}初始化器不允许窄化转换(这通常是好事)并且允许显式构造函数(这没有问题,我们就是要初始化一个新变量)

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(注意)

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

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

由于这个原因,{}初始化经常被称为“统一初始化”(虽然很不幸还存在很少的例外。)

Note(注意)

用一个单值初始化一个用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

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

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

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

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

使用直接的{}初始化,除非你就是想禁止显式构造函数。

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

Enforcement(实施建议)

“C++怎么使用{}初始化器语法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. 在Linux系统中使用GDB来调试C++程序的方法
  2. go语言相对于c/c++的优势有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:怎么进行Android Studio 的简单使用

下一篇:C#如何实现基于Socket套接字的网络通信封装

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》