是否可以将所有权从void *转移到unique_ptr? [英] Is it possible to transfer ownership from a void* to a unique_ptr?

查看:211
本文介绍了是否可以将所有权从void *转移到unique_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前在某些插件项目中使用 dlopen 函数。

此函数句柄返回 void * ,然后将所有句柄保存到名为 handles 的地图中:

I am currently using the dlopen functions for some plugin project.
This function handle returns a void* and then I save all the handle to a map named handles:

void* handle = dlopen(path.c_str(), RTLD_LAZY);  
handles[file] = handle;

我的目标是将所有权传递给地图,我想到了 unique_ptr ,但不确定是否有可能。

My goal is to pass the ownership to the map, I was thinking of a unique_ptr, but not sure if this is even possible.

如果不可能的话,我还有其他选择吗?

If it's not possible what other alternatives do I have ?

推荐答案

如果我理解正确,您可以执行以下操作

If I understand correctly you can do something like

定义关闭函数和指针类型的别名:

Define a close function and an alias for the pointer type:

auto closeFunc = [](void* vp) {
  dlclose(vp);
};
using HandlePtr = std::unique_ptr<void, decltype(closeFunc)>;
std::map<std::string, HandlePtr> handles;

然后创建控点并添加到地图:

and then create the handles and add to the map:

void* handle = dlopen(path.c_str(), RTLD_LAZY); 
HandlePtr ptr( handle, closeFunc );

handles[file] = std::move( ptr );

然后,当唯一时,将调用 closeFunc ptr超出范围

Then closeFunc will be called when the unique ptr goes out of scope

可以通过组合以上两行来防止原始指针:

The raw pointer can be prevented by combining the two lines above:

HandlePtr handle(dlopen(path.c_str(), RTLD_LAZY), closeFunc );
handles[file] = std::move( handle );

这利用了 std :: unique_ptr 指定要使用的删除程序。

This makes use of the second argument to the std::unique_ptr that specifies the deleter to use.

PS:地图 s和 unique_ptr s不能按原样播放,取决于C ++,您可能需要一些安置或移动您正在使用的标准。或者使用 shared_ptr 代替。

PS: maps and unique_ptrs don't play well as-is, you might need some emplaces or moves depending on the C++ standard you are using. Or use shared_ptr instead.

这篇关于是否可以将所有权从void *转移到unique_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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