C++ 我可以重载新操作符以避免使用抽象工厂吗?
我想知道是否有可能在不使用抽象工厂的情况下返回接口的特定实现,因此我提出了一个简单的用例 现在,除了有点非正统之外,测试用例还产生了预期的输出C++ 我可以重载新操作符以避免使用抽象工厂吗?,c++,design-patterns,operator-overloading,C++,Design Patterns,Operator Overloading,我想知道是否有可能在不使用抽象工厂的情况下返回接口的特定实现,因此我提出了一个简单的用例 现在,除了有点非正统之外,测试用例还产生了预期的输出 allocating implementation interface ctor implementation ctor 5 implementation dtor interface dtor freeing implementation 然而,我以前从未见过有人以这种方式做事,所以我想知道这种方法是否有根本性的错误 编辑:这样做的目的是在不使用抽象
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;
}
int main()
{
MyInterface *i = new MyInterface;
cout << i->GetNumber() << endl;
delete i;
return 0;
}
#包括“MyInterface.h”
类MyImplementation:公共MyInterface
{
int-someData;
公众:
MyImplementation():MyInterface(0)
{
cout如果在堆栈上创建MyInterface
,这显然会导致问题,因为该位置没有足够的内存用于实现
即使您总是在堆上分配它,由于您重新构造了一个半构造的基类(有人可能会说这违反了“两个不同的对象必须有不同的地址”子句),所以它闻起来像是未定义的行为
不幸的是,我不能说出你试图解决的真正问题,所以我不能给你具体的答案关于这一点。我想最好知道你的动机是什么。我认为新的操作员应该知道要构造的对象的类型。@steven使用特定于平台的实现,完全对调用方隐藏。是的,如果不隐藏我需要的构造函数,我想我运气不好。