So as I understand it to implement RAII properly, if I where to call CreateFont
, I'd wrap that in a class with CreateFont
in the constructor and DeleteObject
in the destructor, so it cleans it up when it goes out of scope.
First question is, won't I end up with ALOT of classes doing that? Especially since the class only has a constructor and destructor.
Second question is, what if I'm calling the CreateFont class in the WndProc, that goes out of scope constantly. So am I supposed to do all my calls to CreateFont
or like LoadBitmap
in the WndMain?
I'm used to calling those functions in WM_CREATE
and cleaning them up in WM_DESTROY
.
You can avoid a lot of repetitious work by using a template to help you. For example if you use boost::shared_ptr
you can do:
#include <boost/shared_ptr.hpp>
#include <functional>
struct Font;
Font *createFont();
void deleteFont(Font*);
int main() {
boost::shared_ptr<Font> font(createFont(), std::ptr_fun(deleteFont));
}
Which saves you writing a custom class to manage the resource. If boost and TR1 or newer aren't available to you it's still possible to implement something similar and generic yourself to assist.
boost::shared_ptr
is reference counted properly, so if you want to create it somewhere and "promote" it to live longer later you can do so by copying it somewhere longer lived before it dies.