2

I'm trying to use smart pointers such as auto_ptr, shared_ptr. However, I don't know how to use it in this situation.

CvMemStorage *storage = cvCreateMemStorage();
... use the pointer ...
cvReleaseMemStorage(&storage);

I'm not sure, but I think that the storage variable is just a malloc'ed memory, not a C++ class object. Is there a way to use the smart pointers for the storage variable?

Thank you.

sbi
  • 219,715
  • 46
  • 258
  • 445
Brian
  • 1,663
  • 5
  • 18
  • 26
  • 1
    There's no way we can tell you how the memory is allocated without seeing the source of `cvCreateMemStorage`. It might be `malloc`ed, it might be `new`ed, it might not be anything, maybe the function `cvCreateMemStorage` always returns `NULL`. – Dominic Rodger May 17 '10 at 07:42
  • 1
    Are you sure that `cvReleaseMemStorage` takes a `CvMemStorage**` instead of a `CvMemStorage*` ? That seems odd. – ereOn May 17 '10 at 07:49
  • Odd indeed, but [it does](http://opencv.willowgarage.com/documentation/dynamic_structures.html#releasememstorage). – Georg Fritzsche May 17 '10 at 07:55
  • @ereOn: yeah, it thakes a CvMemStorage**, I think it may set the pointer to NULL after release resources. – Brian May 17 '10 at 08:07

2 Answers2

9

shared_ptr allows you do specify a custom deallocator. However, looking at the documentation cvReleaseMemStorage() doesn't have the right form (void f(T*)) and you need a wrapper:

void myCvReleaseMemStorage(CvMemStorage* p) {
   cvReleaseMemStorage(&p);
}

shared_ptr<CvMemStorage> sp(cvCreateMemStorage(), &myCvReleaseMemStorage);
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
  • Also note that this feature of `shared_ptr` is often underestimated. For an `auto_ptr` to work, the user needs to know how to release it, however with an `auto_ptr` you specify how to release at construction time, and then it's hidden away and the user never needs to worry about it. And of course the default is a classic `delete` call. – Matthieu M. May 17 '10 at 12:58
1

The shared_ptr class allows for you to provide a custom delete function/functor, you could simply wrap the cvReleaseMemStorage function in a function and provide that for shared_ptr along with the pointer you want it to manage for you?

Jacob
  • 3,626
  • 2
  • 20
  • 26