如何使用unique_ptr与在c库中分配的数据? [英] How to use unique_ptr with data allocated within a c library?

查看:320
本文介绍了如何使用unique_ptr与在c库中分配的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c + +,我在一个c库写一个包装。我工作的c库函数采用类型LDAPMessage **作为参数,它将在函数内为您分配内存。正常使用方式如下:

I'm in c++ and i'm writing a wrapper around a c library. The c library function i'm working with takes a type 'LDAPMessage **' as a parameter, where it will allocate the memory for you within the function. Normal usage looks like this:

LDAPMessage * msg;
c_lib_function(&msg); // allocates the memory for me



现在我想在这种情况下使用unique_ptr, 。假设我的删除者'LDAPMessageDeleter'存在并在以下工作。

Now I want to use unique_ptr in this case, with a custom deleter. Assume my deleter 'LDAPMessageDeleter' exists and works in the following.

unique_ptr<LDAPMessage*, LDAPMessageDeleter> msg_ptr(new LDAPMessage*);
c_lib_function(msg_ptr.get());

虽然这为我编译,我得到了seg故障。这段代码可能在这里吗?这是否正确使用unique_ptr?

Though this compiles for me, i'm getting a seg fault. Could this code be at fault here? Is this correct usage of unique_ptr?

推荐答案

这可能更容易做

LDAPMessage* msg;
c_lib_function(&msg);

// Now we have out pointer (hopefully)
std::unique_ptr<LDAPMessage, LDAPMessageDeleter> msg_ptr(msg);

当然, LDAPMessageDeleter 释放内存的适当函数(例如 free 是内存分配有 malloc )。

Of course, the LDAPMessageDeleter have to call the proper function to free the memory (e.g. free is the memory was allocated with malloc).

问题中显示的代码的问题是,您尝试创建指向指针的指针,但不要

The problem with the code you show in the question, is that you try to create a pointer to a pointer, but don't make that first-level pointer actually point anywhere.

您在代码中有效地执行的操作是:

What you are effectively doing in your code is this:

LDAPMessage** msg;
c_lib_function(msg);

C库中发生了什么,是指针通过引用传递。因为C实际上没有适当的引用,它的类型是通过传递指针。并且通过使用address-operator传递指针的地址(然后它成为指针的指针)来传递引用到指针。

What's happening in the C library, is that the pointer is passed "by reference". Since C doesn't actually have proper references, it's kind of emulated by passing pointers. And passing a "reference" to a pointer is done by using the address-operator to pass the address of the pointer (which then becomes a pointer to the pointer).

这篇关于如何使用unique_ptr与在c库中分配的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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