Reputation: 539
If you allocate some space dynamically for example
struct node*py=new struct node;
struct node*tr=py;
delete py;
shouldn't the allocated memory still remain and not be freed since I do have another pointer pointing to the same address before the original pointer to the same is deleted?
Upvotes: 0
Views: 867
Reputation: 8126
no, the heap manager just does what it's told and frees the memory.
If you want to retain the memory based on how many references you have to the memory, then consider using reference-counted pointers such as C++11 shared_ptr (see, e.g., Dr Dobbs) or boost's smart pointers.
Upvotes: 4
Reputation: 1998
No, in c/c++ the compiler/execution environment does not track refrences to memory, new and free mark memory as in use or not in use, and any refrence counting or other higher order garbage collection is left up to your program.
Upvotes: 1
Reputation: 163287
No. That's simply not how memory allocation works in C++.
If you allocate memory with new
, and then you call delete
on it, it will get deleted. The memory manager has no facility for canceling or aborting a deletion once it's begun. C++ has a tendency of doing exactly what you ask it to do, so if you don't really want to free some memory, then don't call delete
on it yet.
If you want reference counting, try using std::shared_ptr
(or boost::shared_ptr
, if you don't have the one in std
yet).
Upvotes: 4
Reputation: 654
But you said it yourself - its only a pointer, therefore it doesnt know to what it points. it simply points to somewhere blindfolded.
Upvotes: 2