使用 () 或 {} 正确初始化现代 C++(C++11 及更高版本)中的变量?
C++ 参考页面说 () 用于值初始化,{} 用于值、聚合和列表初始化.那么,如果我只想初始化值,我应该使用哪一个?() 或者 {}?我之所以这么问是因为在 Bjarne 本人的C++ 之旅"一书中,他似乎更喜欢使用 {},即使是用于值初始化(例如参见第 6 页和第 7 页),所以我认为总是使用 {},甚至用于值初始化.然而,我最近被下面的错误严重咬伤了.考虑以下代码.
The C++ reference pages say that () is for value initialisation, {} is for value and aggregate and list initialisation. So, if I just want value initialisation, which one do I use? () or {}? I'm asking because in the book "A Tour of C++" by Bjarne himself, he seems to prefer using {}, even for value initialisation (see for example pages 6 and 7), and so I thought it was good practice to always use {}, even for value initialisation. However, I've been badly bitten by the following bug recently. Consider the following code.
auto p = std::make_shared<int>(3);
auto q{ p };
auto r(p);
现在根据编译器(Visual Studio 2013),q
的类型是 std::initializer_list
,这不是什么我本来打算的.我真正想要的 q
实际上是 r
是什么,即 std::shared_ptr
.所以在这种情况下,我应该不使用 {} 进行值初始化,而是使用 ().鉴于此,为什么 Bjarne 在他的书中似乎仍然更喜欢使用 {} 进行值初始化?例如,他在第 6 页底部使用了 double d2{2.3}
.
Now according to the compiler (Visual Studio 2013), q
has type std::initializer_list<std::shared_ptr<int>>
, which is not what I intended. What I actually intended for q
is actually what r
is, which is std::shared_ptr<int>
. So in this case, I should not use {} for value initialisation, but use (). Given this, why does Bjarne in his book still seem to prefer to use {} for value initialisation? For example, he uses double d2{2.3}
at the bottom of page 6.
要明确回答我的问题,我应该什么时候使用 () 以及什么时候应该使用 {}?这是语法正确性的问题还是良好的编程习惯问题?
To definitively answer my questions, when should I use () and when should I use {}? And is it a matter of syntax correctness or a matter of good programming practice?
哦,呃,如果可能的话,请用简单的英语.
Oh and uh, plain English if possible please.
似乎我有点误解了 值初始化 (请参阅下面的答案).然而,上述问题仍然普遍存在.
It seems that I've slightly misunderstood value initialisation (see answers below). However the questions above still stands by and large.
推荐答案
这是我的看法.
当使用 auto
作为类型说明符时,使用起来更简洁:
When using auto
as type specifier, it's cleaner to use:
auto q = p; // Type of q is same as type of p
auto r = {p}; // Type of r is std::initializer_list<...>
使用显式类型说明符时,最好使用 {}
而不是 ()
.
When using explicit type specifier, it's better to use {}
instead of ()
.
int a{}; // Value initialized to 0
int b(); // Declares a function (the most vexing parse)
可以使用
int a = 0; // Value initialized to 0
但是,表格
int a{};
也可以用于初始化用户定义类型的对象.例如
can be used to value initialize objects of user defined types too. E.g.
struct Foo
{
int a;
double b;
};
Foo f1 = 0; // Not allowed.
Foo f1{}; // Zero initialized.
相关文章