2010-06-27 4 views
3

일부 기본 추상 형식에서 파생 된 개체를 저장하기 위해 boost에서 ptr_map을 사용하고 있습니다.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의이 참조를 반환! 그래서 constructur에서 값에서 유형을 호출 할 수 있습니다. 이제 컴파일러는 오류와 함께 실패 값에 대한 포인터를 반환 ptr_map 어떤 방법이

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’ 

경우, 어떤 문제가있을 수 woudln't. 이것에 대해 뭐라 할 수 있니?

답변

4

실제로 존재하지 않는다면 operator []가 키를 인스턴스화합니다. 열쇠는 추상적이기 때문에 이것은 귀하의 경우에 문제가됩니다. 대신에 at()를 사용하십시오. 이다 ,

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

는 더 많은 정보를 위해, 나는 누구의 매우 목적으로 메모리 관리를 완화하는 컨테이너에 저장된 원시 포인터를 노출하는 당신의 디자인 결정에 의문을 제기 것, BTW "Semantics: lookup" 섹션

를 참조하십시오.

+0

아마 : operator []는 키가 아닌 값/객체를 인스턴스화합니다. 또한, 핵심은 여기서 추상적이지 않습니다. –