覆盖operator new时编译器错误

时间:2012-01-01 16:42:13

标签: c++ memory-management operator-overloading malloc

我不明白为什么在尝试编译时会出现编译器错误:

void* MemoryManagedObject::operator new(size_t size, bool UseMemPool)
{
    Engine* engine = Engine::GetEngine();
    void* alloc;

    alloc = engine->GetMemoryManager()->Allocate(size, UseMemPool);

    if (alloc && UseMemPool)
        mAllocatedWithMemPool = true;

    return alloc;
}

它表示“在静态成员函数中无效使用成员MemoryManagedObject :: mAllocatedWithMemPool”。

基本上,我有一个标志,指出在分配类实例时我是使用了内存池还是只使用了malloc(),我想在覆盖'new'时设置它。

我想在使用类实例之前必须返回'new'方法?有没有办法解决这个问题?

编辑:好奇,这段代码也是一个有效的解决方案吗?

void* MemoryManagedObject::operator new(size_t size, bool UseMemPool)
{
    Engine* engine = Engine::GetEngine();
    MemoryManagedObject* alloc;

    alloc = (MemoryManagedObject*)engine->GetMemoryManager()->Allocate(size, UseMemPool);

    if (alloc && UseMemPool)
        alloc->mAllocatedWithMemPool = true;

    return alloc;
}

2 个答案:

答案 0 :(得分:3)

此错误基本上告诉您不能在静态方法中使用类的成员 成员变量与保存它的实例(您的“this”指针)链接。 静态方法与您的类的实例无关(这使其成为“静态”。它属于yoir类的所有实例。)
当您尝试在静态方法中使用成员变量时,编译器无法知道此成员变量属于您的类的哪个实例,因为该方法属于所有这些实例。

答案 1 :(得分:3)

operator new()(和operator delete())的每次重载都会隐式自动声明static。这是C ++中的一项特殊规则。

因此,您应该设计您的类,以便构造函数还可以记住它是如何分配的,如果您需要保留该信息:

Foo * p = new (true) Foo(true);

也就是说,你的课程看起来像这样:

class Foo
{
    bool mAllocatedWithMemPool;
public:
    static void * operator new(std::size_t n, bool usePool);
    static void operator delete(bool) throw();
    explicit Foo(bool usePool);
    /* ... */
};

请注意,总是声明匹配的delete运算符,即使它的使用非常有限。

相关问题