C++:带有unknow deleter的unique_ptr

peo*_*oro 2 c++ pointers memory-management unique-ptr

我需要编写一个函数来检索和处理一些数据.这些数据可以通过多种方式分配(在数据段,堆上,共享内存段等):

T *data;
if( global ) data = &d;
if( heap )   data = new T [ size ];
if( shm )    data = (T*) shmat( id, 0, 0 );
// processing data ...
Run Code Online (Sandbox Code Playgroud)

既然data可以动态分配,我认为处理它的最好方法是使用一种unique_ptr或其他类型的智能指针.然而,它并不总是动态分配:我需要在运行时选择删除器unique_ptr,但这是不可能的.

我该如何定义和处理data

ken*_*ytm 6

您可以使自定义删除器获取运行时值!

struct MyCustomDeleter
{
   MemoryType type;
   template <typename T>
   void operator()(T* value) const
   {
      switch (type)
      {
         case MemoryType::heap:
             delete[] value;
             break;
         case MemoryType::shm:
             unmap_from_shm(value);
             break;
         // etc.
      }
   }
};

...

std::unique_ptr<T, MyCustomDeleter> ptr (new T[size], 
                                         MyCustomDeleter{MemoryType::heap});
Run Code Online (Sandbox Code Playgroud)