“删除”指针而不破坏数据 [英] "delete" pointer without destroying data

查看:210
本文介绍了“删除”指针而不破坏数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手。我正在分配一个缓冲区:

I'm relatively new to C++. I'm allocating a buffer:

uint8 *buffer = new uint8[len];

使用第三方库,我使用一个img对象的方法以接管缓冲区作为原始图像数据:

Using a 3rd party library, I use a method of an "img" object (it's a picture) to "take over" the buffer as raw image data:

img->SetBuffer((uint8*)data);

我怀疑接管在实践中意味着img对象有自己的指针之后SetBuffer指向缓冲区中的数据。这一切都很好,但我的编译器抱怨(这是一个警告,而不是错误)内存泄漏。如果我添加这一行:删除缓冲区后SetBuffer,警告消失,但同时我的img结束空白(没有数据)。如何避免编译器警告并保留数据?有没有办法只删除缓冲区指针本身,而不破坏它指向的数据?后来在代码中,我删除了img对象,我想无论如何擦除所有的图像数据。

I suspect that "taking over" in practice means that the "img" object has its own pointer which after "SetBuffer" points to the data in "buffer". It all works fine, but my compiler complains (it's a warning, not an error) about a memory leak. If I add this line: "delete buffer;" after SetBuffer, the warning goes away, but at the same time my "img" ends up blank (no data). How do I avoid the compiler warning and keep the data? Is there a way to delete just the "buffer" pointer itself, without destroying the data it points to? Later on in the code, I delete the "img" object, which I guess wipes out all the image data anyway.

推荐答案

如果 img 不释放其缓冲区,一旦您发布 img

if img doesn"t deallocate its buffer, you have to once you release img.

delete img;
delete [] buffer;

这篇关于“删除”指针而不破坏数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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