Re: code for boost shared safe pointer
pauldepstein@att.net wrote:
struct AStructIDontUnderstand
{
template < typename T >
void operator() ( T* ) {}
};
I have been unable to understand the purpose of the above code. As I
understand it, it is used to handle boost shared safe pointers and is
a "deallocation function"
I would be grateful if someone could enlighten me at an elementary
level.
Thank you very much for your help.
Paul Epstein
In the simplest case, memory is allocated with new and deallocated with
delete. It should be no surprise then that the simplest use of a
shared_ptr is to construct it with a pointer to memory allocated by new,
which it will deallocate with delete.
Reality isn't always that simple though. For example, on several
platforms memory must be deallocated in the same dynamic library that
allocated it. Or perhaps you are using a library that was written in C,
and it provides a cleanup function to deallocate complex structures that
it previously allocated for you.
In these cases, you'd like to reuse all the reference counting logic of
a shared_ptr, but it is not suitable to use delete to free the memory.
So, shared_ptr lets you provide it with a deallocation function that it
will use, instead of delete, to free the memory.
As an even simpler example, let's say I wanted to use a shared_ptr to
manage the lifetime of a dynamically allocated array. delete is not
suitable to deallocate an array (delete[] must be used). So, one option
I might choose would be to write something like:
struct Foo { /* ... */ };
Foo * allocFooArray(std::size_t n) { return new Foo[n]; }
void freeFooArray(Foo * p) { delete [] p; }
shared_ptr<Foo> pFoo(allocFooArray(20), freeFooArray);
When the last copy of pFoo goes out of scope, instead of calling delete
on its internal pointer, it will call freeFooArray, correctly deleting
the dynamically allocated array.
shared_ptr goes one step farther, and not only allows you to specify a
pointer to a deallocation function, but rather any object that can be
called like a function (often called a Function Object or Functor,
commonly used throughout the standard library). That is, it can be
either a function pointer or an instance of some class that overloads
operator(), which is what you have in 'AStructIDontUnderstand'.
--
Alan Johnson