Memory deleting problem

Here is my Object code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
	class Object {

	private:

		std::string name;

		sf::Drawable* drawable; //from SFML library

		sf::Transformable* transformable; //from SFML library

	public:

		Object() = default;

		Object(std::string object_name, sf::Drawable* object_drawable, sf::Transformable* object_transformable) : name(object_name), drawable(object_drawable), transformable(object_transformable) {}

		const std::string* getName() {
			
			return &name;
		}

		const sf::Drawable* getDrawable() {

			return drawable;
		}

		const sf::Transformable* getTransformable() {

			return transformable;
		}

	};


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.

sf::RectangleShape http://www.sfml-dev.org/documentation/2.0/classsf_1_1RectangleShape.php
Last edited on
How do I fix this?
This is supposed to be done in the destructor. You should always initialize the pointer at least with nullptr.

You may consider to use smart pointer. Either unique_ptr or shared_ptr:

http://www.cplusplus.com/reference/memory/unique_ptr/
http://www.cplusplus.com/reference/memory/shared_ptr/
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.
Last edited on
Topic archived. No new replies allowed.