2013-05-30 30 views
1

我想知道是否有可能返回不使用抽象工廠的接口的特定實現,所以我把一個簡單的用例。我可以重載operator new以避免使用抽象工廠嗎?

現在,除了有點不正規之外,測試用例還產生了預期的輸出。

allocating implementation 
interface ctor 
implementation ctor 
5 
implementation dtor 
interface dtor 
freeing implementation 

但是,我從來沒有見過任何人這樣做事,所以我想知道,如果有什麼根本性的錯誤了這種方法。

編輯:這樣做的目的是在不使用抽象工廠或pimpl設計模式的情況下從調用者隱藏特定於平臺的代碼。

MyInterface.h

class MyInterface 
{ 
public: 
    MyInterface(); 
    MyInterface(int); 
    virtual ~MyInterface(); 

    void *operator new(size_t sz); 
    void operator delete(void *ptr); 

    virtual int GetNumber(){ return 0; } 
}; 

MyImplementation.cpp

#include "MyInterface.h" 

class MyImplementation : public MyInterface 
{ 
    int someData; 
public: 
    MyImplementation() : MyInterface(0) 
    { 
     cout << "implementation ctor" << endl; 
     someData = 5; 
    } 

    virtual ~MyImplementation() 
    { 
     cout << "implementation dtor" << endl; 
    } 

    void *operator new(size_t, void *ptr) 
    { 
     return ptr; 
    } 

    void operator delete(void*, void*){} 

    void operator delete(void *ptr) 
    { 
     cout << "freeing implementation" << endl; 
     free(ptr); 
    } 

    virtual int GetNumber() { return someData; } 
}; 

///////////////////////// 
void* MyInterface::operator new(size_t sz) 
{ 
    cout << "allocating implementation" << endl; 
    return malloc(sizeof(MyImplementation)); 
} 

void MyInterface::operator delete(void *ptr) 
{ 
    // won't be called 
} 

MyInterface::MyInterface() 
{ 
    new (this) MyImplementation; 
} 

MyInterface::MyInterface(int) 
{ 
    cout << "interface ctor" << endl; 
} 

MyInterface::~MyInterface() 
{ 
    cout << "interface dtor" << endl; 
} 

Test.cpp的

int main() 
{ 
    MyInterface *i = new MyInterface; 

    cout << i->GetNumber() << endl; 

    delete i; 

    return 0; 
} 
+0

我認爲這很好,知道你的動機是什麼。 –

+0

我認爲新操作員應該知道要構建的對象的類型。 – doptimusprime

+0

@steven使用平臺特定的實現方式對調用者完全隱藏。 – bitwise

回答

2

如果CRE在堆棧上吃了一個MyInterface這顯然會導致問題,因爲在該位置沒有足夠的內存來執行。

即使您始終將其分配到堆上,它也會因爲您重構一個半結構化的基類(可能會認爲這違反了「兩個不同的對象必須具有不同地址」子句)而聞起來像未定義的行爲。

不幸的是,我不能說出你想解決的問題,所以我不能'給你具體的答案。

+0

是真的,並且沒有隱藏我需要的構造函數,我想我運氣不好。 – bitwise

相關問題