c++ - std::throw_with_nested 期望异常的虚拟基类的默认构造函数?

标签 c++ c++11 exception libstdc++

为什么这不能编译(尝试使用 Clang 3.4.2 和 GCC 版本 4.7.4、4.8.3 和 4.9.1):

#include <exception>

struct Base {
  inline Base(int) {}
  virtual void f() {}
};

struct Derived: virtual Base {
  inline Derived() : Base(42) {}
};

int main() {
  std::throw_with_nested(Derived());
  return 0;
}

来自 GCC 4.9.1 的错误:

In file included from /usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/exception:163:0,
                from test.cpp:1:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h: In instantiation of 'std::_Nested_exception<_Except>::_Nested_exception(_Except&&) [with _Except = Derived]':
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:126:60:   required from 'void std::__throw_with_nested(_Ex&&, ...) [with _Ex = Derived]'
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:140:58:   required from 'void std::throw_with_nested(_Ex) [with _Ex = Derived]'
test.cpp:13:35:   required from here
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:81:45: error: no matching function for call to 'Base::Base()'
      : _Except(static_cast<_Except&&>(__ex))
                                            ^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:81:45: note: candidates are:
test.cpp:4:10: note: Base::Base(int)
  inline Base(int) {}
          ^
test.cpp:4:10: note:   candidate expects 1 argument, 0 provided
test.cpp:3:8: note: constexpr Base::Base(const Base&)
struct Base {
        ^
test.cpp:3:8: note:   candidate expects 1 argument, 0 provided
test.cpp:3:8: note: constexpr Base::Base(Base&&)
test.cpp:3:8: note:   candidate expects 1 argument, 0 provided

如果我省略 virtual 关键字,我不会出错。这是 GCC 和 Clang 或 libstd++ 错误,还是我做错了什么?

PS:请注意,virtual void f() {}this 的解决方法bug .

最佳答案

问题是当你有虚拟继承时,最后一个派生类负责构造基类。

在这种情况下,库正在尝试创建更多派生自您的类,但无法构造它们。

当您删除“虚拟”继承时,最终类可以毫无问题地派生自您的类。

遇到错误消息的实现“代码”...

template<typename _Except>
struct _Nested_exception : public _Except, public nested_exception 
{
  explicit _Nested_exception(_Except&& __ex)
  : _Except(static_cast<_Except&&>(__ex))
 { }
};

因此它需要在其构造函数中构造一个 Base,因为它现在是最派生的类,并且不能如此正确地 dp。

关于c++ - std::throw_with_nested 期望异常的虚拟基类的默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324582/

相关文章:

c++ - 我如何分析完整的 C++ 构建?

c++ - 自定义预览面板 - 适用于 Windows 7,不适用于 Vista

c++ - 用于 std::list 和 std::map 的 Visual C++11 堆栈分配器

c# - Web API OWIN 启动异常处理

java - 有些事情可能会出错,但也不异常(exception)

c++ - 如何使用 IOCTL_DISK_GROW_PARTITION?

c++ - 在哪里可以获取 C++ 中为我自己的容器创建迭代器的示例代码?

c++ - 引用限定的成员函数作为模板参数?

c++ - decltype 的模板参数数量不正确。

java - 输入不匹配异常