gpt4 book ai didi

c++ - 删除堆上存储数据的堆上对象

转载 作者:行者123 更新时间:2023-11-30 04:07:27 27 4
gpt4 key购买 nike

我的程序是使用 SDL 库中的类编写的。

我有以下类(class):

class s_group
{
private:
SDL_Surface* image;
unsigned int* F_total;
float* F_length;
SDL_Rect** F;
float* F_current;
unsigned int S_total;
unsigned int S_current;

public:
s_group(void);
virtual ~s_group(void);

bool setup( const char* filename, unsigned int s );
//other member functions
};

每个私有(private)成员指针都存储在堆上声明的内存位置,由成员函数 setup 分配。

bool s_group::setup( const char* filename, unsigned int s )
{
s_group::~s_group();//delete already allocated heap memory
if(!load_file(image, filename))
{
image = NULL;
return false;
}

S_total = s;
F = new SDL_Rect*[S_total];
F_total = new unsigned int[S_total];
F_length = new float[S_total];
F_current = new float[S_total];

for(unsigned int index = 0; index < S_total; ++index)
{
F[index] = NULL;
F_total[index] = 0;
F_length[index] = 0.f;
F_current[index] = 0.f;
}
//loop for each array slot and set values of data
return true;
}

在一个大函数中,我在堆上创建了一个此类的对象,将其地址存储在名为 sparkles_group 指针中。

s_group* sparkle = new s_group;
sparkle->setup("sparkle_final.png", 1 );

函数完成后,我调用delete 重新分配堆内存。删除此行可以解决问题,但是会出现内存泄漏。

delete sparkle; 
sparkle = NULL;

这将调用类的析构函数,我认为这是由于内部使用 delete 运算符而发生错误的地方。

s_group::~s_group(void)
{
SDL_FreeSurface(image);
image = NULL;

for(unsigned int s = 0; s < S_total; ++s)
{
for(unsigned int f = 0; f < F_total[s]; ++f)
{
F[s][f].x = 0;
F[s][f].y = 0;
F[s][f].w = 0;
F[s][f].h = 0;
}
delete[] F[s];
F[s] = NULL;
}
delete[] F;
F = NULL;

delete[] F_total;
F_total = NULL;

delete[] F_length;
F_length = NULL;

delete[] F_current;
F_current = NULL;

S_total = 0;
S_current = 0;
}

到达删除运算符时,会出现一个对话框,说明:

Windows has triggered a breakpoint in Program.exe. This may be due to a corruption of the heap, which indicates a bug in Program.exe or any of the DLLs it has loaded.

如何在不导致堆损坏的情况下删除该对象?

最佳答案

来自 effective C++ Scott Meyers

第 9 条:在构造或销毁过程中永远不要调用虚函数。

You shouldn't call virtual functions during construction or destruction, because the calls won't do what you think, and if they did, you'd still be unhappy. If you're a recovering Java or C# programmer, pay close attention to this Item, because this is a place where those languages zig, while C++ zags.

实际上,即使你应该定义你的析构函数,强行调用它也是不可能的

关于c++ - 删除堆上存储数据的堆上对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22513871/

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