What, in C++, determines that a heap allocated object to be referenced? In his book, Data Structures and Algorithm Analysis in C++, Mark Allen Weiss writes "When an object is allocated by new is no longer referenced, the delete operation must be applied to the object (through a pointer)" I find this sentence a bit confusing, all I understand is that a pointer holds a reference to a memory address, but how is the object that represents this address referenced by something else? And when that something else is no longer referencing it, I have to call delete?
I wouldn't get too obsessed with the precise choice of language there. What he's trying to say is that if you allocate an object on the heap, it's your responsibility to de-allocate it when you're done with it. Otherwise, it will remain valid and waste memory.
You can be completely done with an object even though it's still referenced. And precisely when you remove all references to the object and when you de-allocate it is up to you. The point is simply that you definitely don't want to try to use it after you de-allocate and and you also don't want to fail to de-allocate a large number of objects over a long period of time and waste memory.
Fortunately, in modern C++, you have a number of tools to make this much easier including move semantics, unique_ptr
, and many more.