Re: correctly cleaning up and exiting the app.

From: Karl Heinz Buchegger (kbuchegg_at_gascad.at)
Date: 01/17/05


Date: Mon, 17 Jan 2005 10:05:26 +0100

Val wrote:
>
> Aha, my fears seem to justified. There is no correct clean up after all. But I don't know how to fix it.
> When in main() :
>
> delete LookupMenu;
>
> is executed then Menu::~menu() is invoked. This goes well.
> But when ( in main() )
>
> MainMenu
>
> goes out of scope then the destructor Menu::~Menu()
> is invoked again but the program errors on that.
>
> Perhaps "LookupMenu" ( in main() ) shouldn't be deleted in main(), but then the destructor clears only 2 items.
> That can't be correct either since I have 4 times allocated with "new".
> So my question remians: how do I clean up properly, without knowing how many layers of menu's there will be in advance.
>

The important point and what you should be getting into is to
devide pointers into 2 categories:
* owning pointers
* non owning pointers

The difference is as follows: An owning pointer is one, that is responsible
of managing the object, the pointer points to. A non owning is the opposite,
it is just a pointer and nothing else.

Well. In your Menu class in the vector, all the Command pointers are owning pointers,
since the Menu will delete the objects through them, before the Menu object itself
gets destroyed.

So when you pass a pointer to Menu::add(), you really transfer ownership to that
Menu class. Meaning: After that add(), there is no longer ownership of that
pointer in main(), but in the Menu class. Thus main() no longer has the responsibility,
nor the right to delete. It is all done in Menu::~Menu, since the ownership is there.

-- 
Karl Heinz Buchegger
kbuchegg@gascad.at


Relevant Pages

  • Re: Smart Pointers and Microsoft Foundation Classes
    ... LockProxy operator++{ ... lock l; ... problems that come with raw pointers, such as the need to delete them at ... Ownership is always important. ...
    (microsoft.public.vc.mfc)
  • Re: Smart Pointers and Microsoft Foundation Classes
    ... so what not spawn a new tab in the document window. ... problems that come with raw pointers, such as the need to delete them at ... important which is why I started pondering smart pointers in the first ... Ownership is always important. ...
    (microsoft.public.vc.mfc)
  • Re: how to confirm origin of memory leakage
    ... > yes, in the case of threads, I am ok with using raw pointers. ... std::auto_ptr was created to solve a single problem but can introduce more ... They cannot share ownership ... Cannot be used for the STL containers as they do not meet all of the ...
    (microsoft.public.vc.mfc)
  • Re: Questions about memmove
    ... >structures (which may contain pointers). ... What "ownership and duplication issues" would using memmoveto ... copy structs containing pointers have that copying them with = ...
    (comp.lang.c)