C++可运行类

发布于 2024-12-22 23:52:00 字数 474 浏览 3 评论 0原文

我想实现类似于 Java 接口 Runnable 的东西。我尝试这样做:

class Runnable{
    public:
        void start(){
            t = std::thread(&Runnable::run, this);
        }
    protected:
        virtual void run(){
        }
};

想法很简单。我想重载 run 方法,然后 start() 应该启动重载的方法。但是……这不起作用。

terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted

PS 我使用 dlopen 从动态库加载派生自 Runnable 的类实例。

I'd like to achieve something similar to interface Runnable from Java. I try to do that in that way:

class Runnable{
    public:
        void start(){
            t = std::thread(&Runnable::run, this);
        }
    protected:
        virtual void run(){
        }
};

Idea is simple. I'd like to overload run method and then start() should launch overloaded one. But... it doesn't work.

terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted

PS I load an instance of class, which derives from Runnable, from dynamic library with dlopen.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

咆哮 2024-12-29 23:52:00

当 GCC 忘记在命令行中使用 -pthread 时,通常会出现此错误。

This error is commonly seen produced by GCC when forgetting to use -pthread at command line.

·深蓝 2024-12-29 23:52:00

我发现您的代码存在一个问题:不允许您从类的构造函数中调用虚函数。这样做会产生未定义的行为。

I see one problem with your code: You are not allowed to call virtual functions from the constructor of the class. Doing so yields undefined behaviour.

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