在考虑对齐要求的同时一般重载 operator new

Generically overloading operator new while considering alignment requirements

情况

我正在为动态内存(取消)分配编写一个内存管理器。对于 class Aoperator new(或 delete)被调用时使用它,class Aclass CustomAllocate 继承就足够了,class CustomAllocate 本身重载 newdelete 以使用内存管理器的方式。

问题

但是,显然我完全错过了对齐要求。不幸的是,CustomAllocate::new 没有关于从它继承的 class A 应该如何对齐的信息,因为唯一的参数是请求的内存大小。我正在寻找一种方法来包含对齐信息,而不必在每个 class A 中重载 new(和 delete)以使用内存管理器。

想法 1(以及为什么它不起作用)

用表示对齐要求的整数值模板化 class CustomAllocate 并像这样继承:class A : public CustomAllocate< alignof(A) >.

不可能,因为 alignof(A) 在必须作为模板参数传递时无法得知,即使传递的参数永远不会改变 class A.

的对齐要求

想法 2(以及为什么它不起作用)

通过复制粘贴 return alignof(A);.

之类的内容,在每个 class A 中实现一个纯虚函数 virtual int CustomAllocate::getAlignment() = 0

不可能,因为 new 是静态的,因此永远无法访问虚函数。


有什么可行的想法吗?

令我有些惊讶的是,以下似乎有效:

template <typename T> class CustomAllocate
{
public:
    void* operator new (std::size_t count)
    {
        std::cout << "Calling new, aligment = " << alignof (T) << "\n";
        return aligned_alloc (alignof (T), count);
    }

    void operator delete (void *p)
    {
        std::cout << "Calling delete\n";
        free (p);
    }
};

测试程序:

class A : public CustomAllocate <A>
{
public:
    A (int a, int b) : a (a), b (b) { }
    int a, b;
};

int main ()
{
    A *x = new A (1, 2);
    std::cout << x->a << ", " << x->b << "\n";
    delete x;
}

输出:

Calling new, aligment = 4
1, 2
Calling delete

Live Demo