在考虑对中要求的同时,使操作员新手普遍超负荷工作 [英] Generically overloading operator new while considering alignment requirements
问题描述
我正在编写用于动态内存分配的内存管理器.对于class A
在调用operator new
(或delete
)时使用它,class A
从class CustomAllocate
继承就足够了,而class CustomAllocate
本身以new
和delete
重载的方式使用内存管理器.
I am writing a memory manager for dynamic memory (de)allocations. For a class A
to use it when operator new
(or delete
) is called, it is sufficient for class A
to inherit from a class CustomAllocate
, which itself overloads new
and delete
in a way that uses the memory manager.
但是,显然我完全错过了对齐要求.不幸的是,CustomAllocate::new
没有关于class A
的继承方式的信息,因为唯一的参数是所请求内存的大小.我正在寻找一种包括对齐信息的方法,而不必在每个class A
中都重载new
(和delete
)来使用内存管理器.
However, apparently I completely missed out on alignment requirements. Unfortunately, CustomAllocate::new
has no information about how a class A
inheriting from it should be aligned as the only parameter is the size of the requested memory. I am searching for a way to include alignment information without having to overload new
(and delete
) in every class A
to use the memory manager.
使用一个表示对齐要求的整数值对class CustomAllocate
进行模板化,并且继承如下:class A : public CustomAllocate< alignof(A) >
.
Templating class CustomAllocate
with an integer value representing the alignment requirements and inheriting like so: class A : public CustomAllocate< alignof(A) >
.
不可能,因为即使必须通过alignof(A)
永远不要更改class A
的对齐要求,也不能在必须将alignof(A)
作为模板参数传递时知道它.
Impossible because alignof(A)
cannot be known at the time it has to be passed as template parameter, even though the passed parameter should never change the alignment requirements of class A
.
具有纯虚拟功能virtual int CustomAllocate::getAlignment() = 0
,该功能在每个class A
中都可以通过复制粘贴return alignof(A);
之类的东西来实现.
Having a pure virtual function virtual int CustomAllocate::getAlignment() = 0
that is implemented in every class A
by copy pasting something like return alignof(A);
.
不可能,因为new
是静态的,因此永远无法访问虚拟函数.
Impossible because new
is static and thus can never access a virtual function.
任何可行的想法吗?
推荐答案
令我惊讶的是,以下方法似乎可行:
Somewhat to my surprise, the following seems to work:
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
这篇关于在考虑对中要求的同时,使操作员新手普遍超负荷工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!