Proper use of shared_ptr to eliminate freeing between DLL boundaries

I read " Using shared_ptr in dll interfaces ". In this article, phlipsy suggested a way to pass a specific implementation object across the boundaries of a DLL at the end of its answer. Basically, the idea is to return the raw pointer from the DLL and initialize shared_ptr to the EXE w / raw raw pointer.

I do not think this is correct. Let me reprogram it for simplicity.

 // wrong version?? // DLL Object* createObject() { return new Object; } // EXE std::tr1::shared_ptr<Object> p(createObject()); .. 

When an object freed, the destruction context / heap used by shared_ptr is different from that used in the DLL at build time.

The correct way to use shared_ptr is to allocate resources on the same line with shared_ptr initialization so that allocation and release 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()); .. 

I'm right?

+4
source share
2 answers

You are right with both statements. The second correct way is to return the raw createObject (..) pointer, initialize shared_ptr with it, and pass the user deleter to shared_ptr. A custom delector is a library function such as releaseObject (..).

Edit: With your version (createObject (..) returns shared_ptr <..>), you are tied to the specific implementation of the shared_ptr library and the library user. At my suggestion, this restriction is gone.

+6
source

The general rule is that memory allocation / deallocation should always be done from the same module. This way you can create a generic pointer with a dispenser that calls the correct delete method in the dispenser.

The rules that apply to source pointers still apply, even if you wrap them in a smart pointer.

+1
source

All Articles