返回没有动态内存分配的多态类型?

时间:2015-04-01 00:24:48

标签: c++ polymorphism return-value

是否有标准设计模式,我可以从过程返回多态类型,而不需要为过程中的对象动态分配内存?

或者多态性和动态内存分配在实践中是否必然相辅相成?

我希望有一个与C ++ 03兼容的解决方案,但如果有一个C ++ 11,那么我也有兴趣看到它。

1 个答案:

答案 0 :(得分:0)

Object Pool

实际上这是为了提高性能,减少分配;但是,假设您对对象的实例数有限制,它似乎适用于您的方案。以下代码说明了这个想法。这需要事先了解所涉及的类型(因为您需要分配必要的对象缓冲区)。删除(将类型返回到池)也需要小心并了解类型。这可以通过虚函数调用来完成。

template< typename Type >
struct TypePool
{
    static TypePool& GetInstance(){ return pool; }

    Type& GetPooledObject() 
    {
        return arr[0]; // do some real tracking here
    }

  private:
    static TypePool< Type > pool;
    Type arr[10];
};

struct A{ };
struct B : public A { };
struct C : public A { };

// The catch to this design...
TypePool<A> TypePool<A>::pool;
TypePool<B> TypePool<B>::pool;
TypePool<C> TypePool<C>::pool;

struct ObjectFactory
{
    // Actual function you would call to construct the object
    // ObjectFactory::GetType< A > or GetType< B >
    template< typename Type >
    static A& GetType()
    {
        return TypePool<A>::GetInstance().GetPooledObject();
    }
};


int main( int argc, char* r[] )
{
    A& object = ObjectFactory::GetType< C >();
}
相关问题