在考虑对中要求的同时,使操作员新手普遍超负荷工作 [英] Generically overloading operator new while considering alignment requirements

查看:85
本文介绍了在考虑对中要求的同时,使操作员新手普遍超负荷工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写用于动态内存分配的内存管理器.对于class A在调用operator new(或delete)时使用它,class Aclass CustomAllocate继承就足够了,而class CustomAllocate本身以newdelete重载的方式使用内存管理器.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆