c++ - 重写 operator new 时编译器错误

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

最佳答案

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/

相关文章:

iphone - 自定义 UIView 内存泄漏 - iPhone/iPad/iOS 应用程序开发

objective-c - 在 nil 上调用 Block_copy() 和 Block_release() 是否安全?

c++ - 使用正则表达式分割特殊字符

c++ - 'fprintf' 颜色格式包装器

c++ - 像 GTA IV 这样的游戏如何不碎片化堆?

c++ - 如何在处理负数的 C/C++/Obj-C 中编写模 (%) 运算符

c++ - 使用指针成员变量重载类中的 + 运算符

c++ - 返回具有重载运算符的拷贝

c++ - 高效的感知重要点 (PIP) 算法。在 R 或 Rcpp 中

c++ - 为什么这个 const 说明符有未指定的行为?