user877329
user877329

Reputation: 6200

GUI and RAII: Cleenup by destructor or window close, Window lifecycle

Say I want to write a wrapper around the windows Window functions. Then I let the Window constructor create a window and associate an internal window procedure which in turn calls virtual function(s).

What is preffered cleanup?

Upvotes: 1

Views: 363

Answers (1)

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

The latter approach (delete this) is problematic if you have other clients referencing it (they are now left with invalid pointer), it forces you to allocate your object on heap and require that you introduce some sort of reference counting.

RAII approach is more sensible. After all, it is ok to have object disappear from screen but still being live (i.e. window is hidden). I don't see why the lifetime of window itself has to be tied to the lifetime of the object. You don't need to create the window in the constructor, and you also don't need to destroy it in destructor. Often, this is solved by providing a flag to the constructor, which controls whether the real window will be destroyed automatically in constructor or not - there are scenarios which require one or the other.

There is also the scenario where you want to temporarily attach the window object to an 'external' HWND - in that case you also need to decouple lifetimes of the object and window, so the first approach doesn't work well.

just my 2 cents.

Upvotes: 2

Related Questions