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

标签 c++ alignment operator-overloading new-operator generic-programming

情况

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

问题

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

想法 1(以及为什么它行不通)

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

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

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

有一个纯虚函数virtual int CustomAllocate::getAlignment() = 0在每个 class A 中实现通过复制粘贴类似 return alignof(A); 的内容.

不可能,因为 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

关于c++ - 在考虑对齐要求的同时一般重载 operator new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53178405/

相关文章:

c++ - 运算符 [] 后的赋值

c++ 源代码到exe

c++ - static 和 const 如何解决不明确的函数调用?

html - 将标题文本保持在与背景容器相关的相同位置

html - 如何使用 CSS 为所有浏览器垂直居中 div 元素?

alignment - 在 LaTex 中将多行单元格中的文本居中

c++ - 在 C++ 中迭代浮点范围

c++ - 我应该创建多个类吗?

operator-overloading - Raku 运算符重载

c# - C++ 运算符重载