Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of shared_ptr to eliminate deallocation across DLL boundaries

Tags:

c++

shared-ptr

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?

like image 806
Eric Z Avatar asked Oct 16 '11 16:10

Eric Z


2 Answers

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.

like image 78
Simon Avatar answered Sep 29 '22 12:09

Simon


The general rule is that allocating/deallocating memory should always be done from the same module. Thus, you can create a shared pointer with an allocator that calls the correct deallocation method in the allocating module.

The rules that apply to raw pointers still apply, even if you've wrapped them in a smart pointer.

like image 39
Michael Price Avatar answered Sep 29 '22 12:09

Michael Price