Win32 -- Object cleanup and global variables
Posted
by
KaiserJohaan
on Stack Overflow
See other posts from Stack Overflow
or by KaiserJohaan
Published on 2010-12-28T00:36:35Z
Indexed on
2010/12/28
1:54 UTC
Read the original article
Hit count: 321
Hello,
I've got a question about global variables and object cleanup in c++.
For example, look at the code here;
case WM_PAINT:
paintText(&hWnd);
break;
void paintText(HWND* hWnd) {
PAINTSTRUCT ps;
HBRUSH hbruzh = CreateSolidBrush(RGB(0,0,0));
HDC hdz = BeginPaint(*hWnd,&ps);
char s1[] = "Name";
char s2[] = "IP";
SelectBrush(hdz,hbruzh);
SelectFont(hdz,hFont);
SetBkMode(hdz,TRANSPARENT);
TextOut(hdz,3,23,s1,sizeof(s1));
TextOut(hdz,10,53,s2,sizeof(s2));
EndPaint(*hWnd,&ps);
DeleteObject(hdz);
DeleteObject(hbruzh); // bad?
DeleteObject(ps); // bad?
}
1)First of all; which objects are good to delete and which ones are NOT good to delete and why? Not 100% sure of this.
2)Since WM_PAINT is called everytime the window is redrawn, would it be better to simply store ps, hdz and hbruzh as global variables instead of re-initializing them everytime? The downside I guess would be tons of global variables in the end >_> but performance-wise would it not be less CPU-consuming? I know it won't matter prolly but I'm just aiming for minimalistic as possible for educational purposes.
3) What about libraries that are loaded in? For example:
//
// Main
//
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow) {
// initialize vars
HWND hWnd;
WNDCLASSEX wc;
HINSTANCE hlib = LoadLibrary("Riched20.dll");
ThishInstance = hInstance;
ZeroMemory(&wc,sizeof(wc));
// set WNDCLASSEX props
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = WindowProc;
wc.hInstance = ThishInstance;
wc.hIcon = LoadIcon(hInstance,MAKEINTRESOURCE(IDI_MYICON));
wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = TEXT("PimpClient");
RegisterClassEx(&wc);
// create main window and display it
hWnd = CreateWindowEx(NULL,
wc.lpszClassName,
TEXT("PimpClient"),
0,
300,
200,
450,
395,
NULL,
NULL,
hInstance,
NULL);
createWindows(&hWnd);
ShowWindow(hWnd,nCmdShow);
// loop message queue
MSG msg;
while (GetMessage(&msg, NULL,0,0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// cleanup?
FreeLibrary(hlib);
return msg.wParam;
}
3cont) is there a reason to FreeLibrary at the end? I mean when the process terminates all resources are freed anyway? And since the library is used to paint text throughout the program, why would I want to free before that?
Cheers
© Stack Overflow or respective owner