繁体   English   中英

我可以重载new运算符以避免使用抽象工厂吗?

[英]Can I overload operator new to avoid an using an abstract factory?

我想知道是否可以在不使用抽象工厂的情况下返回接口的特定实现,所以我提出了一个简单的用例。

现在,除了有点不合常规之外,测试用例还产生了预期的输出。

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;
}

如果在堆栈上创建MyInterface ,则显然会引起问题,因为该位置没有足够的内存来实现。

即使您总是在堆上分配它,它也会闻起来像未定义的行为,因为您在一个半构建的基类上进行了重新构造(可能会争辩说这违反了“两个不同的对象必须具有不同的地址”子句)。

不幸的是,我无法告诉您您要解决的实际问题,因此无法为您提供具体的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM