shared_ptr商店删除程序如何? [英] How does a shared_ptr store deleter?

查看:133
本文介绍了shared_ptr商店删除程序如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解 shared_ptr 如何存储我给它的删除器。



最初,使用 shared_ptr< int> ,我认为它可以使用 std :: function< void(int *)> int *

,但我可以将任何形式的函数(或可调用对象)当作删除器来使用。

如何 shared_ptr 做到这一点?



这是一个愚蠢的问题,我是C ++的新手,原谅我!



编辑:
问题是:我该怎么做?我应该使用什么?任何示例?或者这是一个非常高级的话题?

解决方案

删除程序和分配程序都进行了类型擦除。共享指针管理一个动态分配的私有模板控制对象,该对象通过一个多态基类访问,并存储所有类型特定的状态和功能。

std :: function 使用类似的想法,因为它也是一个删除类型的动态管理器类,但两者通常是完全分开实现的。



结果是两个班都相对昂贵,只有在真正需要时才能使用。否则,更便宜,非多态的非动态解决方案通常更可取。

I can't understand how a shared_ptr can store the deleter that I gave to it.

Initially, using a shared_ptr<int>, i thought it might use an std::function<void(int*)>, but i can give, as a deleter, any kind of function (or callable objects), as long as the first parameter is a int*.

How can shared_ptr do this?

I'm sorry if this is a silly question, I'm new to C++, forgive me!

Edit: The question is: how can I do something like that? What should I use? Any example? Or it is a very advanced topic?

解决方案

The deleter, as well as the allocator, are type-erased. The shared pointer manages a dynamically allocated, private, templated control object, which is accessed through a polymorphic base and which stores all the type-specific state and functionality.

The implementation of std::function uses similar ideas, since it is also a type-erasing dynamic manager class, but both are typically implemented entirely separately.

The upshot is that both classes are comparatively "expensive" and should only be used when they are genuinely necessary. Otherwise, cheaper, non-polymorphic non-dynamic solutions are usually preferable.

这篇关于shared_ptr商店删除程序如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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