正确使用 shared_ptr 来消除跨 DLL 边界的释放 [英] Correct use of shared_ptr to eliminate deallocation across DLL boundaries

查看:43
本文介绍了正确使用 shared_ptr 来消除跨 DLL 边界的释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读在 dll 接口中使用 shared_ptr".在那篇文章中,phlipsy 在他的回答的最后提出了一种方法,可以不跨 DLL 边界传递特定于实现的对象.基本上,这个想法是从 DLL 返回一个原始指针,并使用该原始指针在 EXE 中初始化 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());
..

object 被释放时,shared_ptr 使用的销毁上下文/堆与构建过程中在 DLL 中使用的不同.

When object is deallocated, the destruction context/heap used by shared_ptr is different from that used in DLL during construction.

shared_ptr 的正确使用方法是资源分配应该和shared_ptr 的初始化在同一行,这样分配和释放可以使用相同的堆,如下图.

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());
..

我说得对吗?

推荐答案

这两种说法都是正确的.第二种正确的方法是通过 createObject(..) 返回原始指针,用它初始化 shared_ptr 并将自定义删除器传递给 shared_ptr.自定义删除器是一个类似于 releaseObject(..) 的库函数.

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(..).

对于您的版本(createObject(..) 返回一个 shared_ptr<..>),您将绑定到库和库用户的特定 shared_ptr 实现.在我建议的方式中,此限制已消失.

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.

这篇关于正确使用 shared_ptr 来消除跨 DLL 边界的释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆