初始化字符串时额外花括号 [英] Extra curly braces while initializing a string
问题描述
根据问题此代码的含义是什么,为什么它会工作?我想问下面代码中 s1 和 s2 之间的区别:
int main(){
const char * s1 = {Hello}; //奇怪,但工作如下
const char * s2 =Hello; //普通case
return 0;
}
为什么要使用额外花括号?任何对C ++标准的引用将是有用的。
在C ++ 98(和C ++ 03) ;在第8.5节中:
14 - 如果
T
是标量类型,声明形式
T x = {a};
相当于
T x = a;
在C ++ 11中,这由列表初始化(8.5.4p3)覆盖:如果初始化器列表有一个单独的E型元素,并且T不是一个引用类型或
,那么p>
认为这是与使用大括号初始化标量相同的问题。
According to question What does this code mean and why does it work? I want to ask what difference between s1 and s2 in the code below:
int main() {
const char* s1 = { "Hello" }; // strange but work as followed
const char* s2 = "Hello"; // ordinary case
return 0;
}
Why extra curly braces are permitted? Any reference to C++ standard will be useful.
In C++98 (and C++03) this is pretty simple; in clause 8.5:
14 - If
T
is a scalar type, then a declaration of the formT x = { a };
is equivalent toT x = a;
In C++11 this is covered by list-initialization (8.5.4p3):
[...] if the initializer list has a single element of type E and either T is not a reference type or its referenced type is reference-related to E, the object or reference is initialized from that element [...]
I think this is the same question as Initializing scalars with braces.
这篇关于初始化字符串时额外花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!