gpt4 book ai didi

c++ - 虚方法和this指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:19 25 4
gpt4 key购买 nike

我刚开始学习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com