delete question

Do you have to call a destructor in this situation?

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
class Data
{
public:
	Data()
	{
		for (int i = 0; i < 1000; i++)
		{
			int* x = new int;
			ints.push_back(x);
		}
	}
	~Data()
	{
		for (auto it = ints.begin(); it != ints.end(); it++)
		{
			delete (*it);
		}
	}

private:
	std::vector<int*> ints;


};

int main()
{
std::vector<Data*> datas;

datas.push_back(new Data);

//when I do this, memory isn't freed
datas.erase(datas.end() - 1);

//frees memory when I do this
datas.back()->~Data();
datas.erase(datas.end() - 1);



}


pls help. using task manager to tract memory used/freed.
Last edited on
Never call the destructor manually. I don't know if this is just for testing but don't do it.
Yes, every time you use new you have to use delete. This is still true for STL containers.

1
2
delete datas.back();
datas.erase(datas.end() - 1);

When you use delete it will call ~Data(). Which is set up correctly.

Of course you would use unique_ptr or some other smart pointer 99% of the time if you had to do this. Don't use new/delete unless you "have" to.
http://www.cplusplus.com/reference/memory/unique_ptr/
Last edited on
Ok, thank you! This makes sense.
Topic archived. No new replies allowed.