ptr_map 和指针
我使用 boost 中的 ptr_map 来存储从某些基本抽象类型派生的对象。
class Entity { virtual void foo() = 0; };
class Entity1 : public Entity {};
class Entity2 : public Entity {};
boost::ptr_map<string, Entity> someMap; // We could store pointers for abstract type
插入效果很好:
someMap.insert("someKey", new Entity1());
someMap.insert("someKey", new Entity2());
但没有从地图返回:
template<typename EntityType>
EntityType *GetEntity(const string &entityName)
{
return dynamic_cast<EntityType*>(&someMap[entityName]);
}
GetEntity<Entity1>(entityName);
现在的问题是:ptr_map 的 operator[] 返回引用!所以在构造函数中可能会从值调用类型。 现在编译器失败并出现错误:
instantiated from ‘EntityType* EntityManager::GetEntity(const std::string&) [with EntityType = Entity1, std::string = std::basic_string<char>]’
error: cannot allocate an object of abstract type ‘Entity’
如果 ptr_map 中有任何方法返回指向该值的指针,则不会有任何问题。对此你能说什么?
I'm using ptr_map from boost for storing objects derived from some base abstract type.
class Entity { virtual void foo() = 0; };
class Entity1 : public Entity {};
class Entity2 : public Entity {};
boost::ptr_map<string, Entity> someMap; // We could store pointers for abstract type
Inserting works great:
someMap.insert("someKey", new Entity1());
someMap.insert("someKey", new Entity2());
But not returning from map:
template<typename EntityType>
EntityType *GetEntity(const string &entityName)
{
return dynamic_cast<EntityType*>(&someMap[entityName]);
}
GetEntity<Entity1>(entityName);
Now the problem: operator[] of ptr_map returns reference! So in constructur there could be calling type from value.
Now compiler fails with error:
instantiated from ‘EntityType* EntityManager::GetEntity(const std::string&) [with EntityType = Entity1, std::string = std::basic_string<char>]’
error: cannot allocate an object of abstract type ‘Entity’
If there is any method in ptr_map which returns pointer to the value, there woudln't be any problems. What could you say about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个经常被遗忘的事实是,如果键不存在,operator[] 将实例化该键。这在您的情况下是一个问题,因为密钥是抽象的。
因此,请使用 at()。
也就是说,
有关详细信息,请阅读 " 语义:顺便说一句
,我会质疑您的设计决定,即公开存储在容器中的原始指针,其目的是减轻内存管理。
An oft forgotten fact is that operator[] will instantiate the key if it doesn't exist. This is a problem in your case because the key is abstract.
So instead, use at().
That is,
For more info, read the "Semantics: lookup" section
BTW, I would question your design decision to expose raw pointers stored within container whose very purpose is to alleviate memory management.