Dynamically allocate image in a shared_ptr each frame
I'm trying to use shared_ptr for the first time here, but I'm having some trouble doing this.
I want to get am IplImage every frame and allocate to a shared_ptr class member, releasing the last image. It's something like this:
class Detector {
public:
void Detector::updateImage {
main_image_.reset(cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3));
}
private:
boost::shared_ptr<IplImage> main_image_;
}
I call updateImage in a loop. cvCreateImage dynamically allocates some memory for that image size.
The first time the loop runs, everything works ok. Now, the second time I get a _BLOCK_TYPE_IS_VALID assertion error. This happens when shared_ptr is trying to delete the pointer.
So, assuming I was doing something wrong, I tried many other options like:
if (!main_image_)
main_image_ = boost::shared_ptr<IplImage> (cvCreateImage...
else
main_image_.reset(cvCreateImage...)
Didn't work also. Tried resetting the shared_ptr first, didn't work either. Tried setting a new temporary shared_ptr and assigning to my main_image_ ptr. No success.
Where am I going wrong here? Using regular pointers and releasing the image manually worked like a开发者_高级运维 charm.
Thanks in advance,
Theo
I assume that you're seeing this error in a debug build?
Which method of allocating memory does cvCreateImage()
use? new
or malloc()
? boost::shared_ptr
uses delete
to destroy the memory so there might be a chance that your system detects that the data wasn't allocated the "right way", ie by using new.
If that's the case then you'd have to use a shared_ptr
with a custom deleter (look at the boost docs for more info) so the memory gets released correctly.
精彩评论