作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我刚开始学习 C++,我正在尝试创建具有 Java Thread 类基本功能的 Thread 类。我想做的是创建一个你子类化的类,编写一个 Run 方法(在基类中是纯虚拟的)创建一个子类的对象,调用它的 start 方法,你就有了线程。
问题是在我使用 C++ 的方式中,分派(dispatch)没有正确完成——就像 Run 函数不是虚拟的,基类的 Run 方法被调用了。
这是标题的代码
#ifndef _THREAD_H_
#define _THREAD_H_
#include <pthread.h>
class Thread {
public:
Thread();
void Start();
~Thread();
protected:
virtual void Run() = 0;
private:
static void *RunWrapper(void *);
pthread_t thread;
};
#endif
实现
#include "thread.h"
#include <pthread.h>
Thread::Thread() {
}
void Thread::Start() {
pthread_create(&thread, NULL, Thread::RunWrapper, (void *) this);
}
void *Thread::RunWrapper(void *arg) {
Thread *t = (Thread *) arg;
t->Run();
return arg;
}
Thread::~Thread() {
pthread_join(thread, NULL);
}
以及实际尝试做某事的文件
#include <iostream>
#include "thread.h"
class MyThread : public Thread {
protected:
void Run() {
std::cout << "The thread is runned" << std::endl;
}
};
int main(void) {
MyThread thread;
thread.Start();
return 0;
}
我在过去 10 小时内不断收到的错误是:
pure virtual method called
terminate called without an active exception
最佳答案
问题是您在 main 中的 MyThread 对象在 main 函数返回后立即被销毁,这很可能发生在新线程实际开始调用其 Start 方法之前。
作为销毁过程的一部分,在调用基类析构函数之前,vtable 将被重置为基类的 vtable,因此当稍后运行 RunWrapper 调用时,它最终会触发纯虚方法错误。在已销毁的对象上调用方法会导致未定义的行为,因此任何事情都可能发生;此行为是您的 C++ 编译器如何实现析构函数和堆栈分配的意外。
关于c++ - 虚方法和this指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3835698/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!