+ 2

What happens to dereferenced heap pointers in C++?

If you have a class called A, I can allocate it both on the stack and on the heap. Let's say I allocated it on the heap like so: A* obj = new A; Now, in order to clean this data up, I'd have to delete it: delete obj; However, what if I decide to dereference this pointer and use it as if it was a normal object? A* obj = new A; A normal = *obj; Now I have a regular variable of type A. Now here is my question, does the heap allocation get cleaned up or not? I tested around and the destructor of A does in fact run, but I never called delete on this object, so is the memory still allocated or not? This is something I randomly thought of and I have no clue what the answer is. I have quite a bit of C++ experience and I'm surprised something like this causes me so much trouble.

7th Jul 2021, 3:01 PM
inxanedev!
inxanedev! - avatar
4 Antworten
+ 3
I'm not sure what your experience has been with other languages but C++ is very up-front about it: If you heap-allocate, you have to manually free/delete. What's happening in your case is that when you do: A normal = *obj; a copy of *obj will be created. You can check this yourself by overriding the copy constructor: A(const A& a) { std::cout << "Copied" << std::endl; } One thing you can be sure of: If in your tests you see multiple calls to the destructor, multiple objects have been destroyed, and hence multiple objects have been created. Copies can be pretty insidious and sometimes you'll not notice that an object has been copied. It's often pretty subtle.
7th Jul 2021, 11:59 PM
Schindlabua
Schindlabua - avatar
+ 4
I tried to simulate your illustration, define class A (outside main function), define pointer of A, and an A instance (in main function) But it appears to me, the destructor isn't being used until code execution goes out of scope of main function where I did most of the above. Maybe you need to post a link to your code in Description for further analysis.
7th Jul 2021, 4:31 PM
Ipang
+ 2
Ipang https://code.sololearn.com/caq4jF4qsnHT/?ref=app I also tested trying to delete the pointer after dereferencing anyway. The double free crash only happened when I wrote the line `delete obj;` twice at the end of the main function, so as far as I know, the allocated memory was not in fact freed, but the destructor did run.
7th Jul 2021, 7:37 PM
inxanedev!
inxanedev! - avatar
0
Schindlabua Ah, so it copies the object. That'd make sense, thanks for enlightening me.
8th Jul 2021, 12:07 PM
inxanedev!
inxanedev! - avatar