在线程中调用纯虚拟方法
Invoking a pure virtual method within a thread
当从基类方法中生成线程时,我需要调用纯虚拟方法实现,如下所示。
#include <iostream>
class Foo {
private:
std::thread tr;
public:
virtual void baz() = 0;
void foo() {
this->tr = std::thread([=] { this->baz(); });
}
};
class Bar : public Foo {
public:
void baz() {
std::cout << "In baz" << "n";
}
};
主类...
#include <thread>
#include "test.hpp"
int main(int argc, char* argv[]) {
Bar b;
b.foo();
}
但它失败并显示消息
终止调用而不显示活动异常
称为纯虚拟方法
消息"纯虚拟方法已调用"仅出现在某些失败消息中。我做错了什么?是否与 Bar 或线程被不当破坏有关?
正如伊戈尔在他的评论中指出的那样,你有一个数据竞赛。线程实际上是在Bar
被销毁后执行的(当然,实际的执行顺序没有定义,所以有时你可能会很幸运(。为了防止这种情况,您需要在Bar
被销毁之前tr.join();
。
class Foo {
std::thread tr;
protected:
void join() { tr.join(); }
public:
virtual ~Foo() = default; // ~Foo should be virtual or protected, if Foo contains virtual methods
virtual void baz() = 0;
void foo() {
this->tr = std::thread([=] { this->baz(); });
}
};
class Bar : public Foo {
public:
~Bar() { join(); }
void baz() { std::cout << "In baz" << "n"; }
};
如果要对此进行更多研究,请在各种方法(尤其是析构函数(中添加一些cout
,并在不同位置添加std::this_thread::sleep_for (std::chrono::seconds(1))
。
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 使用模板而不是虚拟方法的管道模式
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 为什么调用没有正文的纯虚拟方法不会导致链接器错误?
- 出于什么目的,非虚拟方法将与C++一起使用?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 如何重写继承的嵌套类中存在的虚拟方法
- 私有虚拟方法有什么用?
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 确保模拟的 GTest 方法覆盖虚拟方法
- CPP 继承虚拟方法解析顺序
- 我是否应该在包含虚拟方法的类上使用'memcpy'?如果没有,如何替换它?
- 用c++中的纯虚拟方法抽象模板类
- 解决虚拟方法的歧义继承的两种方法
- 没有针对完全专用模板类的外联虚拟方法定义