2016-11-29 6 views
0

オペレータnewで使用するために、グローバルを使用せずにクラスに依存する方法を教えてください。クラスオペレータオーバーロードクラスオペレータnew with dependency

私が正しく理解している場合、誰かが自分のタイプのインスタンスを作成するたびに動作をカスタマイズしたい場合は、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