I often wondered
I know that I can create a pointer to an object instance at the same time passing the same pointer as the function argument using the new keyword. Like mine below in the Animation::newFrame function shown in the example below.
However, I also know that, as a general rule, I am responsible for calling delete for the things that I create using new .
So, when I call the Frame constructor as follows:
Frame* myFrame = new Frame(new point(0,0), new point(100,100), new point(50,20));
Where is the responsibility for freeing memory for the 3 points that I created with new in the function call above?
After all, the above 3 new points definitely don't have names for calling delete on.
I always thought that they belong to the scope of the function in which they are called, and they just go out of scope with the function. However, lately I thought that this is not so.
I hope I was clear enough here.
Thanks in advance,
Guy
struct Frame { public: point f_loc; point f_dim; point f_anchor; //the main constructor:: Creates a frame with some specified values Frame(point* loc, point* dim, point* anchor) { f_loc = loc; f_dim = dim; f_anchor = anchor; } }; struct Animation { public: vector<Frame*> frameList; //currFrame will always be >0 so we subtract 1 void Animation::newFrame(int &currFrame) { vector<Frame*>::iterator it;//create a new iterator it = frameList.begin()+((int)currFrame);//that new iterator is //add in a default frame after the current frame frameList.insert( it, new Frame( new point(0,0), new point(100,100), new point(50,20))); currFrame++;//we are now working on the new Frame } //The default constructor for animation. //Will create a new instance with a single empty frame Animation(int &currFrame) { frameList.push_back(new Frame( new point(0,0), new point(0,0), new point(0,0))); currFrame = 1; } };
EDIT: I forgot to mention that this question is purely theoretical. I know that there are much better alternatives to source pointers, such as smart pointers. I ask you to simply deepen your understanding of conventional pointers and how to manage them.
Also the above example is taken from my project, which is actually a mixed C ++ / cli and C ++ (managed and unmanaged classes), so the constructor accepts only point* and does not pass by value ( point ). Since point is an unmanaged structure, therefore, when used in managed code, you need to control yourself, the programmer. :)