我可以在 C++ 中创建匿名的大括号初始化聚合吗?
可以创建一个通过构造函数参数初始化的匿名对象,例如下面的 return 语句中的参数。
struct S {
S(int i_, int j_) : i(i_), j(j_) { }
int i, j;
};
S f()
{
return S(52, 100);
}
int main()
{
cout << f().i << endl;
return 0;
}
但是,是否可以类似地创建一个使用大括号初始值设定项初始化的匿名聚合?例如,是否可以将下面的 f() 主体折叠为不带“s”的单个 return 语句?
struct S {
int i, j;
};
S f()
{
S s = { 52, 100 };
return s;
}
int main()
{
cout << f().i << endl;
return 0;
}
One can create an anonymous object that is initialized through constructor parameters, such as in the return statement, below.
struct S {
S(int i_, int j_) : i(i_), j(j_) { }
int i, j;
};
S f()
{
return S(52, 100);
}
int main()
{
cout << f().i << endl;
return 0;
}
However, can one similarly create an anonymous aggregate that is initialized with a brace initializer? For example, can one collapse the body of f(), below, down to a single return statement without an "s?"
struct S {
int i, j;
};
S f()
{
S s = { 52, 100 };
return s;
}
int main()
{
cout << f().i << endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在当前版本的 C++ 中不能。你将能够在 C++ 0x 中——无论如何我相信。当然,它仍然可以进行修订 - 曾经我相信您能够在 C++ 0x 中指定概念,但那已经消失了......
编辑:参考将是 [dcl.init] (§8.5/1)在N2960。最相关的位是 BNF 中“braced-init-list”的定义(以及文本的最后一位,表示该部分中描述的初始化可以/确实适用于返回值)。
You can't in the current version of C++. You will be able to in C++ 0x -- I believe anyway. Of course, it's still open to revision -- at one time I believed you'd be able to specify concepts in C++ 0x, but that's gone...
Edit: The reference would be [dcl.init] (§8.5/1) in N2960. The most relevant bit is the definition of 'braced-init-list' in the BNF (and the last bit of text, saying that the initialization described in that section can/does apply to return values).
不是在 C++ 中。但您可以在 C99 中使用所谓的复合文字:
[C99: §6.5.2, 6.5.2.5]
[C++98: §5.2.3, 8.5, 12.1, 12.2]
一些 C++ 编译器提供此扩展,但它不是合法的 ISO C++98。例如,g++ 默认会接受此代码,但如果使用
-pedantic
选项进行编译,它将拒绝它。Not in C++. But you can in C99, using so-called compound literals:
[C99: §6.5.2, 6.5.2.5]
[C++98: §5.2.3, 8.5, 12.1, 12.2]
Some C++ compilers provide this as an extension, but it's not legal ISO C++98. For example, g++ will accept this code by default, but if you compile with the
-pedantic
option, it will reject it.您将能够在 C++1x 中的几乎任何地方使用大括号初始化。 (尽管 Comeau 4.3.9 alpha 在 fnieto 的例子中被卡住了。)
You will be able to use brace initialization just about everywhere in C++1x. (Although Comeau 4.3.9 alpha chokes on fnieto's example.)