Correct use of shared_ptr to eliminate deallocation across DLL boundaries

China☆狼群 提交于 2019-12-04 07:49:31

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.

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.

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