初始化标量用大括号 [英] Initializing scalars with braces
问题描述
在C和C ++,可以初始化数组,并使用大括号结构:
int类型的[] = {2,3,5,7};
进入E = {答案,42};
不过,在从2007年谈话,Bjarne的提到这个语法也适用标量。我试了一下:
INT I = {7};
和它的实际工作!什么是落后,允许标量的初始化用大括号什么道理呢?
请注意:我是专门的不的谈论C ++ 11均匀初始化。这是好老C89和C ++ 98。
什么是落后,允许标量的初始化用大括号什么道理呢?
块引用>
INT
是POD。因此,支架初始化是允许在INT
的情况下(以及所有内建类型),因为它使初始化语法的相一致的其他豆荚。另外,我想任何的理的背后C ++ 11的统一初始化语法的,也是(部分),适用于该语法由C ++ 03允许的。这仅仅是C ++ 03没有延伸,以包括非POD类型,如标准集装箱。
我可以看到一个地方,这个初始化是有用的C ++ 03。
模板< typename的T>
无效F()
{
ŧ的obj = {大小()}; // T是POD:内置型或POD结构
// code
}现在这可以用
结构
被实例化其用合适的成员,以及任何算术类型开始的:结构头
{
为size_t的大小; //它是第一构件
// ...
};F<报头GT;(); //身体变得:头OBJ = {大小(); };这是罚款
F<为size_t>(); //身体变得:为size_t的obj = {大小(); };这是罚款另外请注意,POD,是否结构或内置类型,也可以均匀地初始化
头H =头(); //值初始化
INT I = INT(); //值初始化所以我相信的有一个的原因是一致!
In C and C++, one can initialize arrays and structs using braces:
int a[] = {2, 3, 5, 7}; entry e = {"answer", 42};
However, in a talk from 2007, Bjarne mentions that this syntax also works for scalars. I tried it:
int i = {7};
And it actually works! What is the rationale behind allowing the initialization of scalars with braces?
Note: I am specifically not talking about C++11 uniform initialization. This is good old C89 and C++98.
解决方案What is the rationale behind allowing the initialization of scalars with braces?
int
is POD. So the brace initialization is allowed in case ofint
(and for all build-in types), as it makes the initialization-syntax consistent with other PODs.Also, I guess whatever rationale behind C++11 Uniform Initialization Syntax are, are also (partially) applicable to this syntax allowed by C++03. It is just C++03 didn't extend this to include non-pod types such as the standard containers.
I can see one place where this initialization is helpful in C++03.
template<typename T> void f() { T obj = { size() } ; //T is POD: built-in type or pod-struct //code }
Now this can be instantiated with
struct
which begins with a suitable member, as well as any arithmetic type:struct header { size_t size; //it is the first member //... }; f<header>(); //body becomes : header obj = { size(); }; which is fine f<size_t>(); //body becomes : size_t obj = { size(); }; which is fine
Also note that POD, whether struct or built-in types, can also be initialized uniformly as:
header h = header(); //value-initialized int i = int(); //value-initialized
So I believe one reason is consistency!
这篇关于初始化标量用大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!