我不明白为什么我在尝试编译时遇到编译器错误:
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;
}
最佳答案
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
运算符,即使它的使用非常有限。
关于c++ - 重写 operator new 时编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8694208/