C++ 重写运算符new时出现编译器错误

C++ 重写运算符new时出现编译器错误,c++,memory-management,operator-overloading,malloc,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 &am

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

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;
}

此错误基本上告诉您不能在静态方法中使用类的成员。
成员变量与保存它的实例(您的“this”指针)链接。 静态方法与类的实例不关联(这使它成为“静态的”。它属于yoir类的所有实例。)

当您尝试在静态方法中使用成员变量时,编译器无法知道该成员变量属于您的类的哪个实例,因为该方法属于所有这些实例。

对于
操作符new()
(和
操作符delete()
)的每个重载都隐式且自动声明为
静态
。这是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
运算符,即使它的使用非常有限。

好吧,回答您的直接问题:由于
operator new
是一个静态函数,所以会出现编译器错误。
new
方法不是必须返回,而是类实例必须存在。听起来你不想要一个新的
操作符,而是一个包装类。分配器应该分配内存,而不是构造任何对象。因此,它应该返回一个
void*
,而您不能拥有像
alloc->mAllocatedWithMemPool
这样的访问权限。稍后将在返回的内存中调用对象的构造函数。