2016-11-29 29 views
0

如何在運算符new中提供對類的依賴性,而不使用全局?使用依賴性重載類運算符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的實例可用到全班而不使用全球?

對我來說,這看起來不太可能,因此在類與特定全局實例緊密耦合的情況下強制使用不良設計。

回答

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