【问题标题】:overloading class operator new with dependency重载具有依赖关系的类运算符 new
【发布时间】:2016-11-29 20:09:10
【问题描述】:

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

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

如果我有课:

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

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

这对我来说似乎不可能,因此在类与特定全局实例紧密耦合的情况下强制进行糟糕的设计。

【问题讨论】:

    标签: c++ new-operator


    【解决方案1】:

    这个问题似乎解决了你的问题: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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 2014-01-27
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多