{} 可以用于初始化 C++11 中的变量,就像它们用于初始化 C 中的数组和结构一样。
{} 主要是为了提供语法的一致性(使用 {} 初始化将在所有上下文中都有效,而使用赋值运算符或()初始化将在特定上下文中有效)
{} 初始化还有一个优点,它可以防止缩小范围,即当需要 double 型时,它可以防止你提供 int 型,当需要 int 型时,它可以防止你提供 short 型,这样可以帮助减少 bug
注意:{} 不能用于将值传递给函数,只能用于构造新对象
比如,
this->_width{new_width};
这样是不可以的,只能在构造对象时或者构造函数内初始化值使用
// 构造对象 std::string s{'a', 'b', 'c'};
#include <iostream> class Rectangle { public: Rectangle(int new_height, int new_width) : _width{new_height}, _height{new_width} { // 构造函数内初始化 } Rectangle() : _width{}, _height{} {} // constructor void Print() { std::cout << _width << " " << _height << std::endl; } private: int _width; int _height; }; int main() { Rectangle rc(10, 10); rc.Print(); return 0; }
评价:最好使用 {} 去统一初始化,因为它只有优点,没有缺点
Most vexing parse 里提到,在变量声明示例中,首选方法(C++11 起)是统一(大括号)初始化。[6] 这也允许完全省略类型名称:
//Any of the following work: TimeKeeper time_keeper(Timer{}); TimeKeeper time_keeper{Timer()}; TimeKeeper time_keeper{Timer{}}; TimeKeeper time_keeper( {}); TimeKeeper time_keeper{ {}};
拓展阅读:
- C++ Discussion: Use of =, {}, and () as initializers, Which one should I use?
- Is there a difference between int x{}; and int x = 0;?
原文链接: https://www.cnblogs.com/strive-sun/p/16452130.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/190310
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!