c++ - 类内成员初始化器与初始化列表的冲突解决

标签 c++ c++11

让我在问题之前添加以下代码:

struct A
{
  explicit A(int i):a_{i} {}

  int a_
};

struct B
{
  B():mya_{5} {} // Initialize mya_ (again?)

  A mya_{7}; // Initialize mya_
};

struct B我们在 mya_ 的类内初始值设定项之间存在冲突和 mya_B 中初始化的构造函数的初始化列表。根据 C++ 标准如何解决这个问题,mya_.a_ 的最终值应该是多少?什么时候B搭建完成了吗?

最佳答案

初始化列表获胜。如果您有另一个不初始化成员的构造函数,就地初始化将获胜。

例如,

struct B
{
  B():mya_{5} {}
  B(int) {}
  A mya_{7};
};

int main
{
  B b0;    // b.mya_.a_ is 5
  B b(42); // b.mya_.a_ is 7
}

来自12.6.2 初始化基类和成员[class.base.init]

If a given non-static data member has both a brace-or-equal-initializer and a mem-initializer, the initialization specified by the mem-initializer is performed, and the non-static data member’s brace-or-equal-initializer is ignored. [ Example: Given

struct A {
int i = /∗ some integer expression with side effects ∗/ ;
A(int arg) : i(arg) { }
// ...
};

the A(int) constructor will simply initialize i to the value of arg, and the side effects in i’s brace-or-equal- initializer will not take place. — end example ]

关于c++ - 类内成员初始化器与初始化列表的冲突解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991180/

相关文章:

c++ - 如何使用 unsigned char 分配 #define

c++ - C++ 中多线程的 join() 和 detach() 有什么不同?

c++ - 自定义 istream 结束迭代器

c++ - GetClipRgn 的正确用法?

c++ - shared_ptr 的别名构造函数有什么用?

c++11 - 使用 emplace 添加到 std::map 时如何避免临时副本?

c++ - 将对虚类实现的引用作为线程参数传递

c++ - 警告 : returning reference to temporary - strange case (Clarification for Rvalue)

c++ - 如何使内存对齐类的派生类失去对齐

c++ - 使用 C++ 在 vi​​sual studio 中进行套接字编程