CRT虚拟析构函数 [英] CRT virtual destructor

查看:232
本文介绍了CRT虚拟析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个堆腐败,今天造成的不同的CRT设置(MTd MDd)在我的DLL和我的实际项目。
我发现奇怪的是,应用程序只有当我将析构函数设置为虚拟的时候崩溃。
有一个简单的解释吗?我得到,我不能释放不在我的堆上的内存,但是当我把析构函数定义为非虚拟的时候,是什么区别。

I ran into a heap corruption today caused by different CRT settings (MTd MDd) in my dll and my actual project. What I found strange is that the application only crashed when I set the destructor in the dll to be virtual. Is there an easy explanation for that? I get that I can't free memory that's not on my heap, but where exactly is the difference when I define the destructor as non-virtual.

有些代码只是为了使它更清楚

Some Code just to make it a little clearer

DLL

The DLL

#pragma once
class CTestClass
{
public:
    _declspec(dllexport) CTestClass() {};
    _declspec(dllexport) virtual ~CTestClass() {};
};

我的项目

int main(int argc, char* argv[])
{
    CTestClass *foo = new CTestClass;
    delete foo; // Crashes if the destructor is virtual but works if it's not
}


推荐答案

class CTestClass
{
public:
    _declspec(dllexport) CTestClass() {}
    _declspec(dllexport) virtual ~CTestClass() {}
};

__declspec(dllexport) class CTestClass
{
public:
     CTestClass() {}
     virtual ~CTestClass() {}
};

在前一种情况下,指示编译器只导出两个成员函数:CTestClass :: CTestClass和CTestClass ::〜CTestClass()。但在后一种情况下,您将指示编译器导出虚函数表。这个表是必需的,一旦你有一个虚拟析构函数。所以它可能是崩溃的原因。当你的程序试图调用虚拟析构函数时,它在相关的虚拟函数表中查找它,但是它没有被正确初始化,所以我们不知道它到底在哪里。如果你的析构函数不是虚拟的,那么你不需要任何虚拟函数表,一切都很好。

In the former case you instructed a compiler to export only two member functions: CTestClass::CTestClass() and CTestClass::~CTestClass(). But in the latter case you would instruct a compiler to export the table of virtual functions as well. This table is required once you have got a virtual destructor. So it might be the cause of the crash. When your program tries to call virtual destructor, it looks for it in the associated virtual functions table, but it is not initialized properly so we do not know where it is really goes then. If your destructor is not virtual, then you do not need any virtual function table and everything works just fine.

这篇关于CRT虚拟析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆