我想知道是否有可能返回不使用抽象工廠的接口的特定實現,所以我把一個簡單的用例。我可以重載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;
}
我認爲這很好,知道你的動機是什麼。 –
我認爲新操作員應該知道要構建的對象的類型。 – doptimusprime
@steven使用平臺特定的實現方式對調用者完全隱藏。 – bitwise