Correct use of shared_ptr to eliminate deallocation across DLL boundaries

感情迁移 提交于 2019-12-06 03:33:42

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7785576/correct-use-of-shared-ptr-to-eliminate-deallocation-across-dll-boundaries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!