Type erasure in C++: how boost::shared_ptr and boost::function work?(在 C++ 中键入擦除:boost::shared_ptr 和 boost::function 如何工作?)
问题描述
类型擦除 - 你是这么称呼它的吗?
Type erasure - is that how you call it?
boost::shared_ptr
如何存储它的删除器以及 boost::function
如何存储它的函数对象?
How boost::shared_ptr
stores its deleter and how boost::function
stores its function object?
有教这个技巧的教程吗?
Is there any tutorial that teaches the trick?
使用类型擦除函数对象的运行时成本是多少?
What is the run-time cost of using type-erased function objects?
推荐答案
想法很简单,您定义一个基类,该基类具有包含您需要的功能的接口,然后从它继承.由于type erased 类只使用该接口,下面的实际类型是forgotten 和erased.或者,如果唯一需要的接口可以表示为自由函数,您可以存储指向自由函数的指针.
The idea is simple, you define a base class that has an interface with the functionality you need, and then inherit from it. Since the type erased class uses only that interface, the actual type underneath is forgotten and erased. Alternatively, if the only needed interface can be expressed as free functions you can store pointers to the free functions.
namespace detail {
struct deleter_base {
virtual ~deleter_base() {}
virtual void operator()( void* ) = 0;
};
template <typename T>
struct deleter : deleter_base {
virtual void operator()( void* p ) {
delete static_cast<T*>(p);
}
};
}
template <typename T>
class simple_ptr {
T* ptr;
detail::deleter_base* deleter;
public:
template <typename U>
simple_ptr( U* p ) {
ptr = p;
deleter = new detail::deleter<U>();
}
~simple_ptr() {
(*deleter)( ptr );
delete deleter;
}
};
这是一个真正简化的智能指针,但想法就在那里.在 shared_ptr
的特殊情况下,deleter 作为引用计数对象的一部分存储,由指针保存.
This is a really simplified smart pointer, but the idea is there. In the particular case of shared_ptr
, the deleter is stored as part of the reference count object, that is held by pointer.
这篇关于在 C++ 中键入擦除:boost::shared_ptr 和 boost::function 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中键入擦除:boost::shared_ptr 和 boost::function 如何工作?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01