为什么不编译(用Clang 3.4.2和GCC版本尝试4.7.4、4.8.3和4.9.1):
#include <exception>
struct E { E(int) {} };
int main() {
std::throw_with_nested(E(42));
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 'static const std::nested_exception* std::__get_nested_helper<_Ex>::_S_get(const _Ex&) [with _Ex = E]':
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:104:51: required from 'const std::nested_exception* std::__get_nested_exception(const _Ex&) [with _Ex = E]'
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:138:38: required from 'void std::throw_with_nested(_Ex) [with _Ex = E]'
test.cpp:6:31: required from here
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:90:59: error: cannot dynamic_cast '& __ex' (of type 'const struct E*') to type 'const class std::nested_exception*' (source type is not polymorphic)
{ return dynamic_cast<const nested_exception*>(&__ex); }
^Clang 3.4.2中的错误:
In file included from test.cpp:1:
In file included from /usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/exception:163:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:90:16: error: 'E' is not polymorphic
{ return dynamic_cast<const nested_exception*>(&__ex); }
^ ~~~~~
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:104:40: note: in instantiation of member function 'std::__get_nested_helper<E>::_S_get' requested here
{ return __get_nested_helper<_Ex>::_S_get(__ex); }
^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.1/include/g++-v4/bits/nested_exception.h:138:11: note: in instantiation of function template specialization 'std::__get_nested_exception<E>' requested here
if (__get_nested_exception(__ex))
^
test.cpp:6:8: note: in instantiation of function template specialization 'std::throw_with_nested<E>' requested here
std::throw_with_nested(E(42));
^std::throw_with_nested在C++11中是否期望具有多态类型的参数,还是编译器或libstdc++中的bug?
发布于 2014-08-15 10:02:38
发布于 2014-08-15 09:44:35
这似乎是个bug。
标准是关于std::throw_with_nested的
[[noreturn]] template <class T> void throw_with_nested(T&& t);让U成为remove_reference<T>::type.要求:U应为CopyConstructible。 抛出:如果U是一个非联合类类型,它不是从nested_exception派生的,是一个未指定类型的例外,它公开地从U和nested_exception派生,并从std::forward<T>(t)构造,否则是std::forward<T>(t)。 §18.8.6 except.nested
发布于 2014-08-15 10:02:48
它看起来确实像一个bug (参见其他答案),ref§18.8.6/7。如果不是已经从std::nested_exception派生的,则使用来自E和nested_exception的未指定类型。
作为一种建议中的,在修复的同时,明确地将从派生出来,或者将析构函数实现为虚拟;
#include <exception>
struct E : std::nested_exception { E(int) {} };
// Alternative workaround... virtual destructor
// struct E { E(int) {} virtual ~E() {} };
int main() {
try {
std::throw_with_nested(E(42));
return 0;
}
catch (E&) {
}
}样品这里.
https://stackoverflow.com/questions/25324262
复制相似问题