views:

147

answers:

2

For wxWidgets, why do you need to say:

MyFrame *frame = new MyFrame

instead of:

MyFrame frame;

What's the difference between the two? The second one is nicer to read and easier to use but all examples use the first so I wondered what the reason is.

Just to clarify, I know the second version doesn't work, but I'm wondering if there's a specific design decision which leads to having to use the first form instead of the second. TIA.

A: 

If you use 'new' you are allocating the frame on the heap. Otherwise it's allocated on the stack, and will be deleted when the stack frame ends.

PiedPiper
+2  A: 

The first allocates a new MyFrame instance on the heap, and returns a pointer to it. The second creates a new MyFrame instance on the stack directly.

The reason you need to use the first syntax is that you will add this frame (UI element) into another UI element, such as a window. The window will take the pointer to a frame, and add it as a child.

If you use the second syntax, you'd have to pass a pointer to your stack object (&frame), which would compile, but then as soon as your method returned, frame's destructor would get called since frame would go out of scope. This would "break" the reference inside of your window.

Reed Copsey
Thanks. This makes perfect sense. And does this mean that if I terminate the program without cleaning up this allocated memory, that I will create memory leaks?If so, is there an automagic way of doing this. I heard the term RAII used, but seen it only in the case of scoped_ptrs etc. where the things disappear automatically.
bugmenot77
Normally, that would be true. However, on program termination, your OS will clean up all of the resources. Most GUI toolkits (and I believe wxWidgets does) handle resource management (ie: delete calls) of UI elements, IF they've been parented by another UI element. So, for example, if you put your "frame" inside of a window, deleting your window will automatically delete your frame. This is a "feature" of the toolkit, and not the language, though.
Reed Copsey
Thanks for the ludicrously fast responses! :)
bugmenot77
Terminating a program frees all memory allocated by it, so there's no danger of causing a memory leak.
PiedPiper
@bugmenot77: Memory leaks occur as your program is running. You can recreate resources and never free them, and as long as your program is still running, it's memory usage will grow and grow (until you eventually run out). Once your program is killed, though, the memory will get cleaned up.
Reed Copsey
@Reed Copsey: Your second paragraph needs a little editing, because a wxWidgets frame is a top-level window which is (with the exception of MDI child frames) not added to other windows. So it would be better to say that the newly created frame won't be shown or will be shown and then destroyed immediately when the stack is unwound.
mghie