1

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

现在,除了有点不正统之外,测试用例产生了预期的输出。

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

但是,我以前从未见过有人以这种方式做事,所以我想知道这种方法是否存在根本性的错误。

编辑:这样做的目的是在不使用抽象工厂或 pimpl 设计模式的情况下向调用者隐藏特定于平台的代码。

我的界面.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; }
};

我的实现.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;
}

测试.cpp

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

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

    delete i;

    return 0;
}
4

1 回答 1

2

如果您MyInterface在堆栈上创建一个,这显然会导致问题,因为该位置将没有足够的内存用于实现。

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

不幸的是,我无法说出你想要解决的真正问题,所以我不能给你具体的答案。

于 2013-05-30T03:54:41.123 回答