C++自定义例外
我遇到了损坏的编译器,它不允许从 std::exception
(nvcc 3.0) 继承异常。
所以必须创建解决方法:
struct exception {
explicit exception(const char* message) {
what_ = message;
}
virtual const char *what() const throw() { return what_; }
operator std::exception() const {
return std::runtime_error(what_);
}
private:
const char* what_;
};
struct configuration_error : exception {
configuration_error(const char* message)
: exception(message) {}
};
如果不从异常继承,而不是提供强制转换,我会失去一些东西吗?上述情况有必要吗?
谢谢
I have run into broken compiler, which does not allow exceptions to inherit from std::exception
(nvcc 3.0).
so had to create workaround:
struct exception {
explicit exception(const char* message) {
what_ = message;
}
virtual const char *what() const throw() { return what_; }
operator std::exception() const {
return std::runtime_error(what_);
}
private:
const char* what_;
};
struct configuration_error : exception {
configuration_error(const char* message)
: exception(message) {}
};
is there something I am going to lose by not inheriting from exception, instead providing cast? is what necessary in the above case?
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
catch (std::exception)
不会捕获您的异常,并且您也无法将您的异常dynamic_cast
转换为std::exception
。如果你的程序从不做这些事情,那也没关系。不过,就我个人而言,我不会使用这么糟糕的编译器。
catch (std::exception)
will not catch your exception, and you cannotdynamic_cast
your exception tostd::exception
either. If your program never does either of those things, you're fine.Personally I would not use a compiler this broken, though.
您应该升级到 CUDA 3.1。
You should upgrade to CUDA 3.1.
如果您尝试在设备上创建从 std::exception 派生的实例,它将无法工作,因为需要调用 std::exception 构造函数,而这不是设备函数。
抛出并捕捉你自己的类型可能是解决方案。不过,由于它可能永远不会返回到主机代码(C++ 并不能真正处理并行抛出多个异常),因此与 std::exception 的兼容性不应该成为太大的问题。
If you're trying to create an instance of something derived from std::exception on the device, it won't work because the std::exception constructor would need to be called, and that is not a device function.
Throwing and catching your own type is probably the solution. Since it probably will never make it back to host code, though (C++ doesn't really handle throwing multiple exceptions in parallel), compatibility with std::exception shouldn't be too much of an issue.