重载 class 具有依赖性的 operator new

overloading class operator new with dependency

如何在不使用全局的情况下提供对 class 的依赖以便在 operator new 中使用?

如果我理解正确,如果我想在每次有人创建我的类型的实例时自定义行为,那么我必须将 operator new 重载为 class 方法。 class 方法是静态的,无论我是否声明它是静态的。

如果我有 class:

class ComplexNumber
{
public:

    ComplexNumber(double realPart, double complexPart);
    ComplexNumber(const ComplexNumber & rhs);
    virtual ~ComplexNumber();

    void * operator new  (std::size_t count);
    void * operator new[](std::size_t count);

protected:

    double m_realPart;
    double m_complexPart;
};

并且我想使用我创建的自定义内存管理器来进行分配:

void * ComplexNumber::operator new  (std::size_t count)
{
     // I want to use an call IMemoryManager::allocate(size, align);
}

void * ComplexNumber::operator new[](std::size_t count)
{
    // I want to use an call IMemoryManager::allocate(size, align);
}

如何在不使用全局变量的情况下使 class 可以使用 IMemoryManager 实例?

这对我来说似乎不可能,因此迫使 class 与特定全局实例紧密耦合的不良设计。

这个问题似乎可以解决您的问题:C++ - overload operator new and provide additional arguments。 为了完整起见,这是一个最小的工作示例:

#include <iostream>
#include <string>

class A {
  public:
    A(std::string costructor_parameter) {
        std::cout << "Constructor: " << costructor_parameter << std::endl;  
    }
    void* operator new(std::size_t count, std::string new_parameter) {
        std::cout << "New: " << new_parameter << std::endl;
        return malloc(count);
    }
    void f() { std::cout << "Working" << std::endl; }
};


int main() {
    A* a = new("hello") A("world");
    a->f();
    return 0;
}

输出为:

New: hello
Constructor: world
Working