在现代C ++(C ++ 11和更高版本)中,使用()或{}正确初始化变量? [英] Properly initialising variables in modern C++ (C++11 and above), using () or {}?
问题描述
C ++参考页面表示()用于值初始化,{}用于值和聚合以及列表初始化。所以,如果我只是想要值初始化,我使用哪一个? () 要么 {}?我问,因为在Bjarne本人的书C Tour of 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< std :: shared_ptr< int>>
,这不是我的意图。我实际想要的 q
实际上是 r
是, std :: shared_ptr< ; int>
。所以在这种情况下,我应该不使用{}值初始化,但使用()。鉴于此,为什么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.
这篇关于在现代C ++(C ++ 11和更高版本)中,使用()或{}正确初始化变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!