ptr_map和指针 [英] ptr_map and pointer
问题描述
class Entity {virtual void foo ()= 0; };
class Entity1:public Entity {};
class Entity2:public Entity {};
boost :: ptr_map< string,Entity> someMap; //我们可以存储抽象类型的指针
插入效果非常好:
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 [] 返回引用!所以在构造函数中可能会有来自值的调用类型。
现在编译器失败,出现错误:
从'EntityType * EntityManager :: GetEntity(const std :: string& )[with EntityType = Entity1,std :: string = std :: basic_string< char>]'
pre>
错误:无法分配抽象类型Entity的对象
如果ptr_map中有任何方法返回指向该值的指针,那么将不会有任何问题。你可以说这个吗?
解决方案忘记的事实是,如果运算符[]将不会实例化该键存在。这是您的案例中的一个问题,因为密钥是抽象的。
所以使用at()。
也就是说,return dynamic_cast< EntityType *>(& someMap.at(entityName));
有关更多信息,请阅读语义:查找部分
BTW,我会质疑您的设计决定,揭露存储在容器内的原始指针,其目的是缓解内存管理。
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?
解决方案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,
return dynamic_cast<EntityType*>(&someMap.at(entityName));
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.
这篇关于ptr_map和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!