删除复制构造函数会破坏继承的构造函数

2024-01-10

我正在尝试使用 C++11 的构造函数继承功能。以下片段(从某处复制,我不记得从哪里复制)完全正常:

#include <iostream>

struct Base {
  Base() : Base(0) {}
  Base(int a) : Base(a, 0) {}
  Base(int a, double b) { std::cout << "Base(" << a << "," << b << ")" << std::endl; }
};

struct Derived : Base {
  using Base::Base;
  Derived(const Derived& that) = delete;  // This line is the culprit
};

int main(int argc, char* argv[]) {
  Derived d1;
  Derived d2(42);
  Derived d3(42, 3.14);
}

即直到添加注释标记的行;因为那时一切都会崩溃:

> g++ -std=c++11 -o test test.cpp
test.cpp: In function ‘int main(int, char**)’:
test.cpp:18:11: error: no matching function for call to ‘Derived::Derived()’
   Derived d1;
           ^
test.cpp:18:11: note: candidates are:
test.cpp:13:16: note: Derived::Derived(int)
    using Base::Base;
                ^
test.cpp:13:16: note:   candidate expects 1 argument, 0 provided
test.cpp:13:16: note: Derived::Derived(int, double)
test.cpp:13:16: note:   candidate expects 2 arguments, 0 provided

似乎删除复制构造函数也以某种方式使默认构造函数Base无法访问。谷歌搜索这个问题并没有找到任何有用的信息;所以建议这个问题 https://stackoverflow.com/questions/14912800/c11-non-static-member-initializers-and-deleted-copy-constructor,但据我了解,我在这段代码中没有使用复制初始化。有人可以解释一下这里发生的事情吗?

(生成上述消息的编译器是 GCC 4.8.2;但是,clang 返回类似的错误消息。)


问题是用标记复制构造函数delete做到了用户声明的,这实际上删除了该类的默认构造函数(在您的情况下Derived)。该行为可以在这个简单的代码中看到:

struct X
{
    X(const X&) = delete; // now the default constructor is not defined anymore
};

int main() 
{
    X x; // cannot construct X, default constructor is inaccessible 
}

顺便说一句:即使Base::Base()将被继承,编译器会看到它Derived(): Base(){}. But Derived被删除了,所以它不能真正调用Base::Base()。一般来说,一个using Base::Base语句只是相应编译器生成的语法糖Derived(params): Base(params){}.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

删除复制构造函数会破坏继承的构造函数 的相关文章

随机推荐