如何使抽象类正确返回另一个抽象类的具体实例?

问题描述:

我最近重做了我自己的库之一,尝试将接口与实现分离。

I recently reworked one of my own libraries to try out separating interface from implementation. I am having on final issue with a class that is meant to return an instance of another class.

在接口定义中,我做类似于

In the interface definition, I do something like

struct IFoo
{
    virtual const IBar& getBar() = 0;
}

然后在具体的Foo getBar看起来像

and then in the concrete Foo getBar looks like

const IBar& Foo::getBar()
{
    Bar ret = Bar();
    return ret;
}

问题是get会在getBar完成后被删除,当复制构造函数尝试使用Bar时,这样

The problem is ret gets deleted as soon as getBar is done, causing a big crash when the copy constructor tries to use Bar like so

const Bar myBar = myFoo.getBar();

我一直在阅读各种东西,我知道通过引用返回引起的是皱眉,看到任何其他方式(我不想返回Bar *,因为我不想手动删除返回值)。

I have been reading various things, and I know returning by reference is frowned upon, but I do not see any other way (I do not want to return Bar* because I do not want to have to manually delete the return value).

什么是正确的方式一个抽象类返回一个从另一个抽象类派生的具体类的实例?

What is the proper way (if any way exists) for an abstract class to return an instance of a concrete class derived from another abstract class?

注意我没有看到这个解决方案: http://stackoverflow.com/questions/2861270/returning-an-abstract-class-froma-a-函数
但是我不想让返回值静态和线程安全。

Note I did see this solution: http://stackoverflow.com/questions/2861270/returning-an-abstract-class-from-a-function but I do not want to make the return value static and loose thread safety.

使用智能指针。
这些是不再使用时删除的指针(参见例如 http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/smart_ptr.htm )。