在C ++类型擦除:如何提高:: shared_ptr的和boost ::功能的工作? [英] Type erasure in C++: how boost::shared_ptr and boost::function work?

查看:185
本文介绍了在C ++类型擦除:如何提高:: shared_ptr的和boost ::功能的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类型擦除 - 就是你怎么称呼它

Type erasure - is that how you call it?

如何的boost :: shared_ptr的存储其删除器,以及如何的boost ::功能存储其函数对象?

How boost::shared_ptr stores its deleter and how boost::function stores its function object?

有没有教招任何教程?

什么是使用类型的擦除函数对象的运行时间成本?

What is the run-time cost of using type-erased function objects?

推荐答案

的想法很简单,可以定义与您需要的功能接口的基类,然后从它继承。由于的键入被擦除的类只使用该接口的实际类型是下面的忘记的和的被擦除的。或者,如果只需要接口可以是前pressed作为游离功能可以指针存储到自由功能

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 的特殊情况下,的的删除的是受指针持有存储为引用计数对象的一部分。

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 ++类型擦除:如何提高:: shared_ptr的和boost ::功能的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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