如何从包含 boost::shared_ptr 的 std::list 检索数据
我需要帮助尝试检索 std::list
中保存的数据
我正在使用私有 std:: 处理单例控制器类列表
。客户端类将能够通过此控制器类添加/删除/编辑程序使用的具体类对象。
使用 boost::shared_ptr
的原因是我为创建的每个具体类分配了一个唯一的 objID。将实例对象添加到控制器后,用户稍后将能够搜索和删除对象。每个具体类的 Add(....)
和 Remove(...)
重载方法都可以正常工作。
我现在正在尝试创建 getObject(int index)
& setObject(int index)
方法,但似乎无法弄清楚如何将返回的指针转换为具体类。
请指教。
我当前的代码:
//===============================================================
//Singleton.h controller class
private:
static Singleton *mgr;
typedef boost::shared_ptr<boost::any> Shapes_Ptr;
//private static list
static std::list<Shapes_Ptr> shapes;
public:
const Shapes_Ptr getObject( int index) const; //Return Shape
Shapes_Ptr EditObject( const int index ); //Edit Shape
Info(); //Prints contents of instance to console screen
//===============================================================
//Singleton.cpp
//Return Shape
const Shapes_Ptr getObject( int index) const
{
int cc = 0;
if ( (int)shapes.size() > ZERO && index < (int)shapes.size() )
{
list<Shapes_Ptr>::const_iterator i;
for ( i = shapes.begin(); i != shapes.end(); ++i )
{
if ( cc == index )
{
return (*i);
break;
}
else { ++cc; }
}//for-loop
}
}
//Edit Shape
Shapes_Ptr EditObject( const int index )
{
//same code as getObject()...
}
//===============================================================
//main.cpp
Singleton *contrl= Singleton::Instance();
int main()
{
for ( int i=0; i< 2; ++i )
{
contrl->CreateObject(Box2D() );
}
for ( int i = contrl->Begin(); i< contrl->End(); ++i )
{
if ( boost::any_cast<boost::any> (contrl->getObject(i)).type() == typeid(Physics::Box2D) )
{
//Code compiles but crashes on launch....
any_cast<Box2D> (contrl->getObject(i) ).Info(); // <== ERROR CODE
}
//More if checks for other Concrete classes....
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
撇开当前代码的具体问题不谈,我认为您的设计存在问题。
您有一个单例管理器类,它充当一种池,并且正如您所说,为每个对象分配唯一的 ID,以便以后可以找到它们。但你知道什么让代码找到对象吗?指点一下!如果您使用普通池,每个类型层次结构一个(因此不再使用 Boost Any),您可能会发现它同样有用,并且会有更少令人讨厌的 if/else typeid 检查代码(每个人都同意这不是一个好的用途) RTTI,除了糟糕的 OOP 之外)。
那么,你说呢?如果你想要从一个中心位置分配你的对象,并使用指针作为你的唯一 ID,从而避免沿途查找,请放弃这一点,并使用 Boost Pool。
Putting aside whatever the particular issue with your current code is, I think there is an issue with your design.
You have this Singleton manager class that acts as a sort of pool and also as you say assigns unique IDs to each object so they can be found later. But you know what lets code find objects? Pointers! If you use a normal pool, one per type hierarchy (so no more Boost Any), you may find it just as useful, and there will be less nasty if/else typeid-checking code (which everyone would agree is not a good use of RTTI, aside from being poor OOP).
So, what do you say? Chuck this, and use Boost Pool if you want something to allocate your objects from a central place, and use pointers as your unique IDs, thus avoiding lookups along the way.