在 C++ 中键入擦除:boost::shared_ptr 和 boost::function 如何工作?

Type erasure in C++: how boost::shared_ptr and boost::function work?(在 C++ 中键入擦除:boost::shared_ptr 和 boost::function 如何工作?)

本文介绍了在 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 类只使用该接口,下面的实际类型是forgottenerased.或者,如果唯一需要的接口可以表示为自由函数,您可以存储指向自由函数的指针.

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 如何工作?

基础教程推荐