I have a method that has a few pointers as parameters. This method can be called with either named pointers from the callee or dynamically create a pointer to a new object and pass it in as an argument directly as the method is being called.
myClass *myPtr = new myClass(...);
myMethod(myPtr);
Verus
myMethod(new myClass(...));
The problem is that if both of these are valid options, how does one properly free the passed in pointer? Deleting myPtr within myMethod will cause a crash if myPtr is ever accessed again within the program. If I don’t delete myPtr, the second option will cause a memory leak if it is used. There are benefits for using both options so both shouldn’t break the program.
Aside from using STL, what are some solutions to this problem? Would I have to implement my own garbage collector?
I would say, in this case caller should be responsible for freeing the object. You can consider various options, simplest is:
You could also consider some smart pointer options like
std::tr1::shared_ptror something from boost.UPDATE: If your method should be able to get
NULL-pointer as its argument, there’s no problem at all: