什么时候应该使用括号()与Initializer {}语法来初始化C ++ 11中的对象? [英] When should we use parenthesis ( ) vs. initializer { } syntax to initialize objects in C++11?

查看:84
本文介绍了什么时候应该使用括号()与Initializer {}语法来初始化C ++ 11中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已更新

我已经浏览了链接(例如何时使用括号括起的初始值设定项?)何时应使用 {} 大括号初始化,但是没有提供何时使用括号()与初始化器 {} 语法的信息在C ++ 11/14中初始化对象?哪些标准惯例建议在 {} 上使用()

I have gone through links (such as When to use the brace-enclosed initializer?) on when should I use use {} brace initialization, but information is not given on when we should use parenthesis ( ) vs. initializer { } syntax to initialize objects in C++11/14? What standard practices suggest to use () over {}?

在极少数情况下,例如 vector< int> v(10,20); auto v = vector< int>(10,20); ,结果为 std :: vector 包含10个元素。如果使用花括号,则结果为带有2个元素的 std :: vector 。但这取决于调用者的用例:他/她想分配10个元素还是2个元素的向量?

In rare cases, such as vector<int> v(10,20); or auto v = vector<int>(10,20);, the result is a std::vector with 10 elements. If we uses braces, the result is a std::vector with 2 elements. But it depends on the caller use case: either he/she want to allocate vector of 10 elements or 2 elements?

推荐答案

Scott Meyers在他出色的 Effective Modern C ++的项目7中解决了这个问题。他通过两种语法的优缺点进行了总结,并得出结论。

Scott Meyers tackles this issue in Item 7 of his fantastic "Effective Modern C++". He runs through the differences, pros and cons of both syntaxes, and concludes


尚无共识,认为这两种方法都比另一种更好。我的建议是选择一个并持续应用。

There’s no consensus that either approach is better than the other, so my advice is to pick one and apply it consistently.

另一方面,《 C ++核心准则》建议您更喜欢初始化语法,所以也许最好使用默认值。

On the other hand, the C++ Core Guidelines suggest that you prefer the initialiser syntax, so perhaps that's the better default to go for.

这篇关于什么时候应该使用括号()与Initializer {}语法来初始化C ++ 11中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆