<分区>
考虑以下(我认为是非法的)代码:
#include <exception>
#include <string>
using namespace std;
int main()
{
try {
try {
throw string ("x");
}
catch(string& x)
{
throw_with_nested(string("xx"));
}
}
catch(...)
{
auto ep = current_exception();
}
return 0;
}
使用 clang++ 针对 libc++ 编译此代码。
用 g++ 对抗 libstdc++:
In file included from /usr/local/gcc-4.8.1/include/c++/4.8.1/exception:153:0,
from main.cpp:1:
/usr/local/gcc-4.8.1/include/c++/4.8.1/bits/nested_exception.h: In instantiation of �static const std::nested_exception* std::__get_nested_helper<_Ex>::_S_get(const _Ex&) [with _Ex = std::basic_string<char>]�:
/usr/local/gcc-4.8.1/include/c++/4.8.1/bits/nested_exception.h:104:51: required from �const std::nested_exception* std::__get_nested_exception(const _Ex&) [with _Ex = std::basic_string<char>]�
/usr/local/gcc-4.8.1/include/c++/4.8.1/bits/nested_exception.h:138:38: required from �void std::throw_with_nested(_Ex) [with _Ex = std::basic_string<char>]�
main.cpp:15:43: required from here
/usr/local/gcc-4.8.1/include/c++/4.8.1/bits/nested_exception.h:90:59: error: cannot dynamic_cast �& __ex� (of type �const class std::basic_string<char>*�) to type �const class std::nested_exception*� (source type is not polymorphic)
{ return dynamic_cast<const nested_exception*>(&__ex); }
^
据我了解,std::throw_with_nested<T>
要求 T 是多态的,而 std::string 不是多态的。所以 libstdc++ 在这里做正确的事情(tm)。
这里有人可以提供什么吗?