【发布时间】:2012-01-01 16:42:12
【问题描述】:
我不明白为什么在尝试编译时出现编译器错误:
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”时设置它。
我猜“新”方法必须返回才能使用类实例?有没有办法解决这个问题?
编辑:只是好奇,ss 这段代码也是一个有效的解决方案吗?
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是一个静态函数。 -
不是
new方法必须返回,而是类实例必须存在。听起来你不想要一个operator new而是一个包装类。 -
分配器应该分配内存,而不是构造任何对象。因此它应该返回一个
void*,并且您不能拥有像alloc->mAllocatedWithMemPool这样的访问权限。稍后将在您返回的内存上调用对象的构造函数。
标签: c++ memory-management operator-overloading malloc