c++ - 复制省略直接基类初始化?

标签 c++ language-lawyer c++17

以下代码无法同时使用 Gcc 和 Clang 编译,因为 B 基类子对象在 A 构造函数中的复制构造:

struct B{
  B();
  B(const B&) =delete;
  };

struct A:B{
  A():B(B()){} //=> error: use of deleted function...
  };

不过根据 [class.base.init]/7 :

The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of [dcl.init] for direct-initialization.

所以初始化规则对于成员或直接基是相同的。对于成员子对象,Gcc 和 Clang 不使用已删除的复制构造函数:

struct A2:B{
  B b;
  A2():b(B()){} //=> OK the result object of B() is b
  };

这不是 Clang 和 Gcc 的编译器错误吗? B的拷贝构造函数不应该在A()中省略吗?


有趣的是,即使 gcc 检查复制构造是否格式正确,它也会忽略此复制构造函数调用,参见 assembly here

最佳答案

这确实很奇怪。首先,与是否应在此处调用复制构造函数无关,因为 [class.base.init]/7不区分初始化基和初始化成员,两种情况下的行为应该相同。我在标准中找不到任何额外的措辞,它会以某种方式在基的初始化与成员的初始化之间引入不对称。仅基于这一点,我想说我们可以得出结论,这里或多或少存在编译器错误。 icc 和 MSVC 在初始化基类与初始化成员时似乎至少表现一致。但是,icc 和 MSVC 在代码是否应该被接受的问题上存在分歧。

如果我们查看 [class.base.init]/7,我相信可以找到是否应该调用复制构造函数的问题的答案。再次:

The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of [dcl.init] for direct-initialization. […]

强调我的。我相信 [dcl.init] 的相关位应该是 [dcl.init]/17.6 ,我们在哪里找到:

  • If the destination type is a (possibly cv-qualified) class type:

    • If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object. […]

    • Otherwise, if the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated ([over.match.ctor]), and the best one is chosen through overload resolution ([over.match]). […]

[…]

如果要应用 17.6.2,这意味着应该调用复制构造函数,这将使 MSVC 成为本示例中唯一行为正确的主要编译器。但是,我的解释是 17.6.1 一般适用并且 icc 是正确的,即您的代码应该编译。这意味着您在这里所拥有的甚至可能是 GCC 和 clang 中的两个错误(基的初始化与成员的初始化行为不同 + mem-initializer 调用了 copy-ctor,尽管它不应该),还有一个在 MSVC 中……

关于c++ - 复制省略直接基类初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53883664/

相关文章:

c++ - 友元运算符重载导致 "already defined in"链接器错误

c++ - 使用虚函数进行类型转换

c - 如何用 extern 解决新声明的多个先前声明?

c++ - 可变参数模板中的函数参数

c++ - 在不使用 if 语句、字符数组、apstrings 或 atoi 的情况下,如何将具有两位数字的字符串转换为 int?

c++ - 使用 dbus-cpp 列出 WPA 请求者网络属性

c++ - 为什么我们需要语法产生式基本说明符的最后两个定义?

c++ - 值初始化是否适用于原子对象?

c++ - 将 make_shared 与 emplace_back 和 push_back 一起使用 - 有什么区别吗?

c++ - 如何避免 C++17 中的虚拟继承?