【发布时间】:2018-02-26 04:47:50
【问题描述】:
在阅读了 C++11 和围绕它的通用指南之后,我经常阅读有关应该如何使用类内初始化和聚合初始化的信息。
这是一个看似“旧”的做事方式的例子:
class Example
{
public:
// Set "m_x" to "x", "m_y" gets set to the default value of 5
Example(int x) : m_x(x), m_y(5)
{
}
private:
int m_x;
int m_y;
};
据我了解,这是人们现在推荐的:
class Example
{
public:
Example(int x) : m_x{x}
{
}
private:
int m_x{0}; // Supposedly {} works too? I guess this would
// only be necessary if I had another constructor
// taking in 0 arguments, so "m_x" doesn't go uninitialized
int m_y{5};
};
我的问题是:这对指针、引用和某些 STL 类有何影响?这些人的最佳做法是什么?他们只是用{} 初始化吗?此外,即使构造函数初始化变量,我也应该这样做吗? (即写m_x{},即使它被构造函数设置为其他东西)
谢谢。
【问题讨论】:
标签: c++ c++11 stl initialization