Deleting a class stored in a vector

I have class called Entity that I have to dynamically create, so I store it in a vector called EntityList. I am trying to make it so that when I get a certain input, I can delete the entity and remove it from EntityList.

Entity:
1
2
3
4
5
6
7
8
9
10
class Entity
{
private:
//Data members
public:
    Entity();
    ~Entity();    
    void Delete();

};


I didn't put anything in the deconstructor, should I?
 
Entity::~Entity() {}


 
void Entity::Delete() {delete this;}


1
2
3
4
5
//Pseudo code
if (KeyPress = d)
{
EntityList[1].Delete();
}


When I try this, my program crashes with no error and the files I would have written to get corrupted.
Only delete objects that you have created with new.

To remove an element from a vector you can use erase.
http://www.cplusplus.com/reference/vector/vector/erase/
1
2
3
4
if (KeyPress == d)
{
	EntityList.erase(EntityList.begin() + 1);
}
You cannot use delete this; because this will cause undefined behaviour.

If you need to delete a dynamic object from your vector use:
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
33
34
35
36
37
38
39
40
41
42
#include <vector>
#include <string>
#include <iostream>

using std::vector;
using std::string;
using std::cout;
using std::endl;

class Dynamic {
public:
	Dynamic(string name) : name_(name) { };
	~Dynamic() { cout << "Destructor Called: " << name_ << endl; }

	string name_;
};

int main() {
	vector<Dynamic*> vector_;

	vector_.push_back(new Dynamic("dynamic_1"));
	vector_.push_back(new Dynamic("dynamic_2"));
	vector_.push_back(new Dynamic("dynamic_3"));

	cout << "Vector.size() = " << vector_.size() << endl;

	// To delete 1 element and remove it.
	vector<Dynamic*>::iterator iter = vector_.begin() + 1;
	delete *iter;
	vector_.erase(iter);

	cout << "Vector.size() = " << vector_.size() << endl;
	for (unsigned i = 0; i < vector_.size(); ++i)
		cout << "vector_[" << i << "] = " << vector_[i]->name_ << endl;

	/**
	 * Clean up the rest of the vector
	 */
	for (unsigned i = 0; i < vector_.size(); ++i)
		delete vector_[i];
}
Topic archived. No new replies allowed.