在单个列表中存储多个派生类类型 [英] Storing multiple derived class types in a single list
问题描述
我想在同一个stl列表中存储派生自同一个基类的多个类类型。
如果我使用
列表< BaseClass> L;
然后我的代码编译正常,当我添加任何派生类。但是,看起来我的派生类在被存储之前被自动地转换为基本类型。显然,我想存储派生类型的唯一成员。
$ p$ p>
list< BaseClass *> L;
但是这样会出现异常安全的问题超出范围?如果一些异常抛出之前呢?)。所以也许这样:
#include< list>
#include< tr1 / memory>
std :: list< std :: tr1 :: shared_ptr< BaseClass> > L;
会更好。 TR1基本信息。在维基百科上,其文档
在boost文档下。
I want to store multiple class types derived from the same base class in a single stl list.
If I use
list<BaseClass> L;
then my code compiles fine when I add any derived classes. However, it looks like my derived classes are automatically being casted down to the base type before being stored. Obviously I want to store the unique members of the derived types as well. How can I do this?
You have to use
list<BaseClass *> L;
But with this, you will have problems with exception safety (Where do you destroy the object when the list goes out of scope? What if some exception is thrown before?). So maybe this:
#include <list>
#include <tr1/memory>
std::list<std::tr1::shared_ptr<BaseClass> > L;
would be better. TR1 basic info can be found e.g. on wikipedia, its documentation under the boost docs.
这篇关于在单个列表中存储多个派生类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!