ptr_map和指针 [英] ptr_map and pointer
问题描述
我使用ptr_map从boost用于存储从一些基本的抽象类型派生的对象。
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);
现在的问题:ptr_map的运算符[] 返回参考!因此,在constructur有可能是从调用值类型。
现在,编译器失败,错误:
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’
如果有在ptr_map返回指针值的任何方法,有woudln't会有任何问题。你可以说这个怎么样?
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屋!