有没有一个标准的设计模式可以让我从过程中返回一个多态类型,而不需要在过程中为对象动态分配内存?
或者,多态和动态内存分配在实践中一定是齐头并进的吗?
我希望有一个与C++03兼容的解决方案,但如果有C++11的解决方案,我也很感兴趣。
发布于 2015-04-01 08:52:54
这实际上是为了性能,以减少分配;但是,假设您对对象的实例数量有限制,则它似乎适用于您的场景。下面的代码说明了这一想法。这需要先验地了解所涉及的类型(因为您需要分配必要的对象缓冲区)。另外,删除(将类型返回到池中)也需要注意和了解类型。这可以通过虚函数调用来完成。
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 >();
}https://stackoverflow.com/questions/29380823
复制相似问题