Monday, January 14, 2008

Using Custom Deallocator in boost::shared_ptr

Using boost::shared_ptr in the typical situation is quite straightforward. If what you want is to to have your use of new and delete conforms with RAII idiom you will find it as close as coding things in language like Java. However when you need to use it beyond object that is acquired/instantiated the typical way e.g: COM object, it's when you find it's not that obvious.

It's quite simple actually but the standard documentation can be quite confusing if what you want to find is a practical way to do it. I find this discussion shed a light to this issue quite clearly.

It turn out that what you need to do is

  • make a custom deallocator function that takes pointer to the class
  • pass the function name as the second parameter to the shared_ptr's constructor
Here's a sample code snippet for it :
2:void deallocatorFunc(ClassA *p)
4: //deallocate p
7:boost::shared_ptr< ClassA > ptr(new ClassA(), deallocatorFunc);

No comments: