统一初始化语法的使用
Usage of Uniform Initialization Syntax
如果我有class
class Foo
{
public:
Foo();
Foo(int bar);
private:
int m_bar;
}
这两种初始化成员的方式有什么区别
Foo::Foo(int bar):
m_bar(bar)
{
}
Foo::Foo(int bar):
m_bar{ bar }
{
}
有人告诉我在代码审查中使用统一初始化语法,即大括号初始化。在这种情况下有区别吗?还是只是风格偏好?
在简单类型的情况下,例如 int 在您的情况下,没有区别。但是,从STL初始化std::vector会完全不同
std::vector<int> v1(3,1); // v1 consists of: 1, 1, 1
std::vector<int> v2{3,1}; // v2 consists of: 3, 1
看看这个 answer 如果你想知道为什么 通常 大括号 {} 初始化更好,但是引用 Scott Meyer 的书 有效的现代 C++,我强烈推荐:
[...] So why isn’t this Item
entitled something like “Prefer braced initialization syntax”?
The drawback to braced initialization is the sometimes-surprising behavior that
accompanies it. [...]
如果我有class
class Foo
{
public:
Foo();
Foo(int bar);
private:
int m_bar;
}
这两种初始化成员的方式有什么区别
Foo::Foo(int bar):
m_bar(bar)
{
}
Foo::Foo(int bar):
m_bar{ bar }
{
}
有人告诉我在代码审查中使用统一初始化语法,即大括号初始化。在这种情况下有区别吗?还是只是风格偏好?
在简单类型的情况下,例如 int 在您的情况下,没有区别。但是,从STL初始化std::vector会完全不同
std::vector<int> v1(3,1); // v1 consists of: 1, 1, 1
std::vector<int> v2{3,1}; // v2 consists of: 3, 1
看看这个 answer 如果你想知道为什么 通常 大括号 {} 初始化更好,但是引用 Scott Meyer 的书 有效的现代 C++,我强烈推荐:
[...] So why isn’t this Item entitled something like “Prefer braced initialization syntax”? The drawback to braced initialization is the sometimes-surprising behavior that accompanies it. [...]