windows dll memory management and shared_ptr

Started by
-1 comments, last by chairthrower 15 years, 9 months ago
There is a need under windows that memory allocated in one dll, should also be released in that same dll. How does this requirement play with boost::shared_ptr? Since the shared_ptr implementation is a header only library it seems reasonable to suppose that the call to deallocate memory is likely interspersed in any dll where the shared_ptr declaration code has been included. It is possible that this could be a problem even where the objects destructor implementation (called when use_count() hits zero) resides only as a single instance in one cpp file, since the shared_ptr implementation of delete might assume that the memory allocated for the object resides in the current dll even if it knows that it has to reference another dll to invoke the objects actual destructor function. To correct for this - I am considering passing a custom deleter object to the shared pointer which wraps a single function that does the deallocation and destructs the object (by calling delete). My questions are - is it necessary to do this or is there something else going on that I may have misunderstood ? does checked_delete hold have any application here. are the cross dll internal memory needs of shared_ptr and bind safe - presumably yes since they would merely use the global default allocator like other parts of the stl.
// implementation of new and delete are constrained to a single file
// to avoid mismatching new or delete calls across dll boundaries. 

#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

// interface header.hpp
struct instance_type
  : public boost::enable_shared_from_this< instance_type>
{
    typedef instance_type              this_type;
    typedef boost::shared_ptr< this_type>   ptr;

    static ptr create();
    static void destroy( const instance_type *p);
    void init() { } 
    // yada yada yada
};

// instance.cpp  
#include <boost/bind.hpp>
instance_type::ptr instance_type::create()
{
     ptr p( new this_type, boost::bind( &this_type::destroy, _1));
     p->init();
     return p;
}

void instance_type::destroy( const instance_type *p) 
{
     delete p;
}
// main.cpp
main()
{
    instance_type::ptr p = instance_type::create(); 
}

This topic is closed to new replies.

Advertisement