c++ - 什么时候使用初始化列表构造函数?

标签 c++ c++11 initializer-list

在构造函数中使用 {} 而不是 () 将允许我在 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 by std::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/

相关文章:

c++ - 用于 C/C++ 代码的预处理器指令 #ifndef

c++ - 类模板中的 Constexpr 成员函数

c++构造函数重载与initializer_list的歧义

c++ - 使用 "auto"推断嵌套初始值设定项列表的类型

c++ - 返回一个带有随机选项和局部变量的 char 函数

c++ - 从文件中读取数据到struct并将struct添加到 vector (以创建struct的 vector )

c++ - 用于从 C++ 代码中提取函数的正则表达式

c++ - 如何获得比较两个 vector 对的子集?

c++ - 从容器中获取元素的常量资格的通用方法

c++ - 为什么大括号中的标量不被解释为 initializer_list