为什么这不能编译(尝试使用 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++ 错误,还是我做错了什么?
最佳答案
问题是当你有虚拟继承时,最后一个派生类负责构造基类。
在这种情况下,库正在尝试创建更多派生自您的类,但无法构造它们。
当您删除“虚拟”继承时,最终类可以毫无问题地派生自您的类。
遇到错误消息的实现“代码”...
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/