将可释放对象包装为智能指针 [英] Wrapping a releaseable object into a smart pointer

查看:89
本文介绍了将可释放对象包装为智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,智能指针在那里是为了避免内存泄漏等.但是,通常还有一些对象也需要释放,而不是通过freedelete释放.是否有一些将此类指针与模板一起使用的通用方法?

As far as I understand the smart pointers, they are there to avoid memory leaks among other things. However there are often objects which also need to be released, but not by free or delete. Is there some generic way of using such pointers with a template?

FILE为例,完成后应使用fclose.当然,还有其他类型的指针具有自己独特的释放功能.那么,我是否必须实现单独的包装程序以解决其单独的发布方法,还是有一些更好的方法来做到这一点?

As an example FILE comes to mind, which should use fclose when done. Of course there are other kind of pointers with unique release functions of their own. So do I have to implement seperate wrappers to account for their individual release method, or is there some better way to do this?

可以这样使用的东西:

smart_ptr<FILE, fclose> fl = fopen();
smart_ptr<IStream, T->Release> pFileStream = SHCreateStreamOnFile(...);

推荐答案

如果使用的是unique_ptrshared_ptr,则可以提供自定义删除器. unique_ptr的删除器作为模板参数传递,并且

If you are using unique_ptr or shared_ptr, you can provide your custom deleter. The deleter for a unique_ptr is passed as a template parameter, and

删除器必须是FunctionObject或对FunctionObject的左值引用或对函数的左值引用,并且可以使用类型为unique_ptr<T, Deleter>::pointer

对于shated_ptr,应将删除器作为构造函数参数提供.

For the shated_ptr, the deleter should be provided as the constructor parameter.

class Foo
{

};

class Deleter
{
public:
    void operator()(Foo *)
    {
        std::cout << "deleter";
    }
};

int main() {
    std::unique_ptr<Foo, Deleter> ptr(new Foo());
    std::shared_ptr<Foo> ptr1(new Foo(),
                             [](Foo*){std::cout << "deleter for shared_ptr";}
                             );
}

不过,您必须注意不要引起内存泄漏.

You have to be careful not to cause memory leaks, though.

这篇关于将可释放对象包装为智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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