And here is code where object will be stored in std::map<std::string, Object*>
1 2 3 4 5 6 7 8 9 10
void Engine::loadResources() {
sf::RectangleShape* rect = new sf::RectangleShape(sf::Vector2f(500, 500)); //Creates new sf::RectangleShape, because if I do this sf::RectangleShape rect(sf::Vector2f(500, 500)), there would be an error because
//it goes out of scope.
Object* obj = new Object("rectangle", rect, rect); //Creating new Object and storing rectangle's sf::Drawable and sf::Transformable.
addObject(obj); //addObject(Object*); adds Object to std::map<std::string, Object*>
}
In Object class I stored rectangle's sf::Drawable and sf::Transformable. So I thought my code is finished, until I realized if Object needs to be deleted, the Object will be deleted but sf::RectangleShape
will be still alive in memory. How do I fix this? And is this good idea? Creating an Object class with drawable and transformable and storing it in map?
Thanks.
I agree with Coder777, who suggested that you should keep smart pointers to those objects in each Object instance. You should prefer std::unique_ptr over std::shared_ptr where possible.
addObject(Object*) adds Object to std::map<std::string, Object*>
Why are you storing pointers to objects, instead of just objects?
Prefer storing values. The standard containers will perform memory management for you -- but not if you don't store values. In these cases you will need to perform memory management yourself, independent of the life of the map.