gpt4 book ai didi

boost - ptr_map 和指针

转载 作者:行者123 更新时间:2023-12-05 00:55:28 39 4
gpt4 key购买 nike

我正在使用来自 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());

但不从 map 返回:

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 中有任何返回值指针的方法,就不会有任何问题。您对此有何看法?

最佳答案

一个经常被遗忘的事实是,如果键不存在,operator[] 将对其进行实例化。这在您的案例中是一个问题,因为 key 是抽象的。因此,请改用 at()。也就是说,

return dynamic_cast<EntityType*>(&someMap.at(entityName));

有关详细信息,请阅读 "Semantics: lookup"

顺便说一句,我会质疑您公开存储在容器中的原始指针的设计决定,其目的是减轻内存管理。

关于boost - ptr_map 和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3128296/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com