c++ - 我们什么时候不应该在构造函数中使用初始化列表?

标签 c++ constructor

当我们不应该在构造函数中使用初始化列表时,有人可以引用示例代码吗?如何通过赋值来克服这个问题?

我正在寻找以下语句的示例

This might happen when your class has two constructors that need to initialize the this object's data members in different orders. Or it might happen when two data members are self-referential. Or when a data-member needs a reference to the this object, and you want to avoid a compiler warning about using the this keyword prior to the { that begins the constructor's body (when your particular compiler happens to issue that particular warning). Or when you need to do an if/throw test on a variable (parameter, global, etc.) prior to using that variable to initialize one of your this members.

最佳答案

我相信您的声明的作者所指的主要概念是对初始化列表中变量的调用不是您在初始化列表中看到它们的顺序,但是按照变量在类定义中列出的顺序。

这意味着

  • 如果您有两个使用初始化列表的不同构造函数,它们必须以相同的顺序初始化它们
  • 您对排序的控制(如果您有相互依赖的成员,这可能很重要)是有限的

我建议您阅读 Scott Meyer 的 Effective C++,其中涵盖了这一点(以及许多其他有用且信息丰富的主题)。

关于c++ - 我们什么时候不应该在构造函数中使用初始化列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10323739/

相关文章:

c++ - 将左值传递给右值模板参数将不允许我声明 const T& var

C++ 比较一个字节和一个字母

c++ - 用指针初始化 C++ 类是否安全?

c# - 在设计时限制构造函数中参数的值

c++ - 为什么不能将 std::stol 转换为 std::function 对象?

c++ - 错误:没有匹配函数用于构造函数初始化的调用

c++ - 我可以在 OSX 中使用 EGL 吗?

c++ - 无效使用非静态数据成员 C++ Student

c++ - 编译器降低程序的时间复杂度是否合法?这被认为是可观察的行为吗?

C++ - 如何从一个类的构造函数中初始化一个单独类的构造函数?