dimanche 16 août 2020

How to deal with a container of shared_ptrs

Hello I have this situation : Entity has an object called componentContainer wich is like this.

struct ComponentContainer {

public:
ComponentContainer() {};
std::map<std::string, 
std::shared_ptr<Component> >components;

std::shared_ptr<Component> getComponent(std::string name) {
        return components[name];
}



void addComponenet(std::shared_ptr<Component>component, std::string name) {
    
     //NOT REALLY SURE ABOUT THIS
    components[name] = std::move(component);


}

//render the components data in the interface

};

The entity class has a function addComponent like this:

virtual void 
   attachComponent(std::shared_ptr<Component> 
   component) { 
    const char* n = component->name; 
   componentContainer.addComponenet(component, 
   n);
    }

An Entity can have multiple components, components could have reference to other components aswell. When I run the program I can see that the components were actually added to each entity. However when I call getComponent() the component I'm getting is immediately destroyed.

I create components like this :

std::shared_ptr<Component> something = 
std::make_shared<InheritedSomething>(...);

then

 Entity->attachComponent(something);

I need this mechanism of get the component of an entity. Where Am I screwing reference count for the component object itself? Is really a good idea to use shared_ptr in this situation? Could please show mesome code for me to get an idea of how should I do it.

Aucun commentaire:

Enregistrer un commentaire