“delete” pointer without destroying data

天大地大妈咪最大 提交于 2019-12-13 22:02:21

问题


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

uint8 *buffer = new uint8[len];

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);

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.


回答1:


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

delete img;
delete [] buffer;



回答2:


You should read the documentation (or source) of the class (type of *img).

  1. Check whether your assumption is correct about SetBuffer.
  2. Check whether the class deallocates the buffer upon destruction.

If the class does not destroy the buffer itself you'll have to do it after destroying the object img points to.

-edit-

As MSalters correctly noted you should of course use the appropriate allocation scheme if the memory is freed by the class itself (i.e. use new[] with delete[], allocator::allocate() with allocator::deallocate(), malloc() with free()...)

[Rem: Your question indicates that the class does not do any deallocation the way you're using it.]



来源:https://stackoverflow.com/questions/27917516/delete-pointer-without-destroying-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!