专门化一些 class 的 operator new 和 operator delete

specializing operator new and operator delete of some class

为了有选择地跟踪特定类型的分配,我创建了以下结构:

struct my_alloc {
    static void* operator new(size_t sz) { /*...*/ ; return calloc(1,sz); }
    static void operator delete(void *ptr) { /*...*/ ; return free(ptr); }
};

每当我想遵循特定类型的内部分配时,比如 struct A,我可以简单地继承自 my_alloc:

struct A : my_alloc  
{  
    AImpl* p_impl;
    A() {
        p_impl = new AImpl; // will call my_alloc::operator new
    }
    ~A() {
        delete p_impl;
    }
};

A x();  // x.p_impl has been allocated via my_alloc

这对于跟踪标准容器中的分配也很有用:

using Vector = std::vector<some_class, my_alloc>;

Vector v; 
v.reserve(10);   // v.data has been allocated using my_alloc

然而,有时我需要跟踪分配,有时我不需要。 为此,我尝试将分配器作为模板参数传递

template <class ALLOC>
struct A : ALLOC  {   /*...*/   }; 

但它并不总能奏效:

using A_alloced = A<my_alloc>;       // works fine
using A_non_alloced = A;             // does not does not compile

我也考虑过提供一个默认参数:

template <class ALLOC = std::allocator>
struct A : ALLOC  {   /*...*/   }; 

但我缺少 std::allocator 的参数。

PS: 我正在寻找一种也适用于以下类型擦除 class 的公式!请注意 new Model<B>() 调用,其中 Model<T> 在 class...

之外不可见
class MyType {
    struct Concept {
         virtual ~Concept() = default;
         virtual Concept* clone() const = 0;
    };

    template <class T>
    struct Model {
         T data;

         virtual Concept* clone() const { return new Model(*this); }

         template <class B> 
         Model(B value) : data(value) {}
    };

    Concept *self;
public:
    template <class B>
    MyType(B value) : self(new Model<B>(value)) {}
   
    MyType(const MyType &rhs) : self(rhs.self->clone()) { }
    
};

你可能继承自 Empty class:

struct Empty{};

using A_alloced = A<my_alloc>;
using A_non_alloced = A<Empty>; 

allocator 可能是一个错误的名称,尤其是当您想用 std::allocator.

代替时