Lets say I have a object whose purpose is to hold a bunch of pointers for an object type MyObject, and lets say I want a function that adds new MyObjects to the collection like so:
void MyCollection::addObject(){
MyObject *newObject = new MyObject();
MyCollection.add(mycollection, newObject);
}
Lets say that MyCollection.add takes in a particular collection object and a pointer and somehow internally stores it. However the problem with this function is while the newObject itself is persistent, the *newObject pointer gets destroyed after the function call so the add() function no longer has a pointer that really points to the object. Is there any good way to make a persistent pointer somehow?
Thanks
This betrays a huge misunderstanding about how objects and pointers work.
A pointer is an address.
newcreates an object on the heap and returns the address. When you pass that address to the collection the collection gets a copy of the address, which is exactly the same as the address you got fromnew. When the variablenewObjectgoes out of scope and is destroyed, the collection still has the copy of the address, and the address still points to the object. No matter how many copies of the address you make and destroy, the address is still good and the object that the address points to is still good.In fact, the address you get back from
newis a copy of the address thatnewgenerated internally, and that original, internal value is destroyed. And when you sayMyObject *newObject = new MyObject();you’re making another copy. But it doesn’t matter because every copy of the address is as good as every other one.