在构造函数中使用 {}
而不是 ()
将允许我在 header 中使用特定构造函数初始化类成员,如下所示:
class X {
private:
std::vector y{1, 2, 3};
};
但是我怎么知道对于类 Z
我使用 Z z{a, b};
将调用具有两个参数的构造函数 — Z::Z(int a, int b)
— 而不是带有 std::initializer_list
的那个?
我的意思是 std::complex(1, 2)
和 std::complex{1, 2}
是一样的,但是 std::vector (3)
和 std::vector{3}
肯定不是。
我应该始终使用 {}
变体还是使用 ()
除非我需要 {}
?
最佳答案
这是一个可以跨越整本书章节的主题。请参阅 this recent draft Item 中的引述Scott Meyers 即将推出的 Effective Modern C++(为清晰起见重新格式化):
Most developers end up choosing one kind of delimiter as a default, using the other only when they have to.
Braces-by-default folks are attracted by their wide applicability, their prevention of narrowing conversions, and their avoidance of C++’s most vexing parse. Such folks understand that in some cases (e.g., creation of a
std::vector
with a given size and initial element value), parentheses are required.In contrast, the go-parentheses-go crowd embraces parentheses as their default argument delimiter. They’re attracted to its consistency with the C++98 syntactic tradition, its avoidance of the auto-deduced-a-
std::initializer_list
problem, and the knowledge that their object creation calls won’t be inadvertently waylaid bystd::initializer_list
constructors. They concede that sometimes only braces will do (e.g., when creating a container with particular values).Neither approach is rigorously better than the other. My advice is to pick one and apply it consistently.
关于c++ - 什么时候使用初始化列表构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22820017/