情况
我正在为动态内存(取消)分配编写一个内存管理器。对于 class A
在 operator new
时使用它(或 delete
)被调用,对于 class A
就足够了从 class CustomAllocate
继承,它本身会重载 new
和 delete
以使用内存管理器的方式。
问题
但是,显然我完全错过了对齐要求。不幸的是,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
关于c++ - 在考虑对齐要求的同时一般重载 operator new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53178405/