开发者

dynamic_cast reference to base class in stl container

开发者 https://www.devze.com 2023-03-25 21:23 出处:网络
Is it possible to store a bunch of objects by their base class in say an std::list without pointers.I would really like the objects to be held in the container, then retrieve a pointer to the object i

Is it possible to store a bunch of objects by their base class in say an std::list without pointers. I would really like the objects to be held in the container, then retrieve a pointer to the object in the container and dynamic_cast it to correct derived class.

I have it working fine using pointers. Like (super simple version):

class IComponent  
{   
    virtual ~Icomponent(){}  
}  

class PositionComponent: public IComponent  
{  
    //...  
    float x, y;  
}

std::list<IComponent*> CList;

//...  
// fill the list  
// put reference to object in pComponent
//...   

PositionComponent* position = dynamic_cast<PositionComponent*>( pComponent) 

position->x = 346452.235612;

But the memory management is a huge pain. My actual structure is a

map<enumValue, map<int, IComponent*>开发者_如何转开发; >

I get the feeling I can't use the objects themselves because when I add any derived component into the list the extra data will be cut off and leave me with the base class only. This didn't figure this until I tried static_cast instead and it crashed.

Can answer my original question and/or confirm my feelings on the matter. Thanks!


to minimize pain of manual memory management use smart pointers: std::unique_ptr if your compiler already supports it or boost::shared_ptr, but not std::auto_ptr that is not supposed to be used in containers


As you guessed, when you stored an object in a container by value, it gets sliced and the data is chopped off.

If you only need to store one data type (you only show one in your code), then you can make the container hold that type.

If not, you really are stuck using pointers. You can make the memory management much easier by using a smart pointer, or if appropriate, a boost ptr_container of some sort.

Further you might want to think if you need to spend one more iteration considering your design to provide an interface that doesn't require doing a dynamic_cast to get the original type back out again.


Is it possible to store a bunch of objects by their base class in say an std::list without pointers.

This sentence seems to be contrdicted in C++ point of view IMO. Because STL container can only hold same type of object, if you put derived object into a base type container, it got sliced.

So the apparent normal solution is to use container to hold base type pointers like you did(u could use boost/std smart pointer for memory management)

If you really want to store different objects in one STL container, you may want to consider use boost::any.

0

精彩评论

暂无评论...
验证码 换一张
取 消