If you delete an object pointer, will the pointers in the object be deleted?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class X
{
public:
	X()
	{
		y = new int;
	}
	~X()
	{

	}

	int* y;


};

int main()
{
	X* x = new X;

	delete x;
	//is x.y deleted/freed from memory?
}
Last edited on
No. That is the job of X's destructor.

At line 10, add:
 
    delete y;


and you will be fine.
Thanks for the response. Somewhere on stackoverflow someone said, "There is a rule in C++, for every new there is a delete." Is this always true? Why isn't the y pointer deleted if it's contained in object x?
Last edited on
There is a rule in C++, for every new there is a delete." Is this always true?

Yup, that's true.

Why isn't the y pointer deleted if it's contained in object x?

How does the compiler know if y has already been deleted or not? y is simply a variable containing an address. Compiler doesn't know if that address is from the heap, or points to something else. X may not "own" what y points to.

If you want a pointer to be deallocated automatically, use a shared_ptr or a unique_ptr:
http://www.cplusplus.com/reference/memory/shared_ptr/
http://www.cplusplus.com/reference/memory/unique_ptr/


"There is a rule in C++, for every new there is a delete." Is this always true?

Yeah, that's pretty much it, but you have to write the delete (don't forget writing delete!), it does not just magically appear somewhere.

Why isn't the y pointer deleted if it's contained in object x?

Because you never call delete on y, it's as simple as that.
Memory deallocation is the responsibility of the developer.
If you don't want to think about it (which is usually the case) you should use std::shared_ptr or std::unique_ptr
Last edited on
Topic archived. No new replies allowed.