Search code examples
c++shared-ptr

Correct use of shared_ptr to eliminate deallocation across DLL boundaries


I'm reading "Using shared_ptr in dll-interfaces". In that post, phlipsy suggested a way to pass no implementation specific object across DLL boundaries, at the end of his answer. Basically, the idea is to return a raw pointer from DLL and initialize the shared_ptr in EXE w/ that raw pointer.

I don't think it's correct. Let me reprototype it for simplicity.

// wrong version??
// DLL
Object* createObject()
{
  return new Object;
}

// EXE
std::tr1::shared_ptr<Object> p(createObject());
..

When object is deallocated, the destruction context/heap used by shared_ptr is different from that used in DLL during construction.

The right way to use shared_ptr is that resource allocation should be in the same line w/ the initialization of shared_ptr, so that the allocation and deallocation can use the same heap, as shown below.

// right version
// DLL
std::tr1::shared_ptr<Object> createObject()
{
  return std::tr1::shared_ptr<Object>(new Object);
}

// EXE
std::tr1::shared_ptr<Object> p(createObject());
..

Am I right?


Solution

  • You're right with both statements. A second correct way would be to return a raw pointer by createObject(..), initialize a shared_ptr with it and pass a custom deleter to the shared_ptr. The custom deleter is a library function like releaseObject(..).

    Edit: With your version (createObject(..) returns a shared_ptr<..>) you're bound to a specific shared_ptr implementation of the library and the library user. In my proposed way this restriction is gone.