C++ { } 的使用场景
{} 可以用于初始化 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;?

浙公网安备 33010602011771号