使用智能指针包装C创建和销毁函数 [英] Wrapping C create and destroy functions using a smart pointer

查看:192
本文介绍了使用智能指针包装C创建和销毁函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些处理对象创建和销毁的C API,它提供:createObject(...)destroy(...).我想将其包装到一些更现代的构造/破坏机制中,并与智能指针一起使用.恐怕在某个时候我会忘记销毁该对象,否则会发生某些异常.

I have some C API that handles object creation and destruction, it provides: createObject(...) and destroy(...). I want to wrap it into some more modern construction/destruction mechanisms and use them with smart pointers. I am afraid that at some point I will forget to destroy the object, or some exception will occur.

我知道shared_ptr的自定义删除器功能,但是我不能显式调用new,因为createOjbect函数处理初始化.

I am aware of custom deleter function for shared_ptr, but I can't explicitly call new, because createOjbect function handles initialization.

在这种情况下可以使用STL智能指针吗?在这种情况下,我是否必须从头开始实现一个类,该类在构造函数中进行初始化,在析构函数中进行销毁并进行引用计数?

Can I use STL smart pointers in this situation? Do I have to, from scratch, implement a class with initialization in constructor, destruction in destructor and reference counting in this situation?

推荐答案

std::shared_ptr 完全能够使用cutstom创建者和删除者来创建和删除对象,而不是 new ,您必须使用创建者功能.

The std::shared_ptr is fully capable to create and delete an object with cutstom creator and deleter, but instead of new you have to use the creator function.

考虑一下,我们有以下创建者和删除者:

Let's consider, we have the following creator and deleter:

typedef struct {
    int m_int;
    double m_double;
} Foo;

Foo* createObject(int i_val, double d_val) {
    Foo* output = (Foo*)malloc(sizeof(Foo));

    output->m_int = i_val;
    output->m_double = d_val;

    puts("Foo created.");
    return output;
}

void destroy(Foo* obj) {
    free(obj);
    puts("Foo destroyed.");        
}

要管理由以上函数创建的Foo的实例,只需执行以下操作:

To manage an instance of Foo created by functions above, simply do the following:

std::shared_ptr<Foo> foo(createObject(32, 3.14), destroy);


如果您不希望使用 std::shared_ptr 是一项开销共享对象的所有权.在这种情况下, std::unique_ptr 要好得多,但是对于这种类型,您必须定义一个自定义删除函数,通过它可以删除托管的Foo实例:


Using the std::shared_ptr is an overhead if you don't wish to share the object's ownership. In this case the std::unique_ptr is much better but for this type you have to define a custom deleter functor with which it can delete the managed Foo instance:

struct FooDeleter {
    void operator()(Foo* p) const {
        destroy(p);
    }
};
using FooWrapper = std::unique_ptr<Foo, FooDeleter>;

/* ... */

FooWrapper foo(createObject(32, 3.14));

这篇关于使用智能指针包装C创建和销毁函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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