ptr_map and pointer

前端 未结 1 1484
滥情空心
滥情空心 2021-01-14 13:49

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 Enti         


        
相关标签:
1条回答
  • 2021-01-14 13:59

    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.

    0 讨论(0)
提交回复
热议问题