Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

c++ - "delete" pointer without destroying data

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...