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?