ptr_map 和指针 [英] ptr_map and pointer

查看:38
本文介绍了ptr_map 和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 boost 的 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

插入效果很好:

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[]返回引用!所以在构造函数中可以从值中调用类型.现在编译器失败并出现错误:

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中有任何返回值的指针的方法,就不会有任何问题.对此,您有什么想说的吗?

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?

推荐答案

一个经常被遗忘的事实是,如果键不存在,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,

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆