0

How does one provide a dependency to a class for use in operator new, without using a global?

If I understand correctly, if I want to customize the behavior every time someone creates an instance of my type, then I have to overload operator new as a class method. That class method is static, whether I declare it static or not.

If I have a 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;
};

and I want to use an custom memory manager that I created to do the allocation:

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

How do I make an instance of IMemoryManager available to the class without using a global?

It does not seem possible to me, and therefore forces bad design where the class is tightly coupled to a particular global instance.

Christopher Pisz
  • 3,757
  • 4
  • 29
  • 65

1 Answers1

1

This question seems to solve your problem: C++ - overload operator new and provide additional arguments. Just for the sake of completeness, here it is a minimal working example:

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

The output is:

New: hello
Constructor: world
Working
Community
  • 1
  • 1
dario2994
  • 48
  • 6