C++自定义例外

发布于 2024-09-10 05:44:38 字数 574 浏览 4 评论 0原文

我遇到了损坏的编译器,它不允许从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

药祭#氼 2024-09-17 05:44:38

catch (std::exception) 不会捕获您的异常,并且您也无法将您的异常 dynamic_cast 转换为 std::exception 。如果你的程序从不做这些事情,那也没关系。

不过,就我个人而言,我不会使用这么糟糕的编译器。

catch (std::exception) will not catch your exception, and you cannot dynamic_cast your exception to std::exception either. If your program never does either of those things, you're fine.

Personally I would not use a compiler this broken, though.

末蓝 2024-09-17 05:44:38

您应该升级到 CUDA 3.1。

You should upgrade to CUDA 3.1.

和我恋爱吧 2024-09-17 05:44:38

如果您尝试在设备上创建从 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文