Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
(added more stuff )
Howdy'

Small question regarding SelectObject (mosly the Win32 one, not the CDC one).

I'm reviewing a large piece of code that draws text and we query the text metrix after calling SelectObject( fontHandle) but we never keep the old object and never restore the old handle:
(1)
C++
{
 /// ... some code...
 ::SelectObject( validHDC, validHFONT );
 /// ... do something ...
}


normally I'm used to seeing seomthing like
(2)
C++
void f{)
{
 /// ... some code...
 HFONT oldFont = ::SelectObject( validHDC, validHFONT );
 /// ... do something ...

 ::SelectObject( validHDC, oldFont);
}




Will that cause a lot of issues (resource leaks and/or performance) if I do (1) instead of (2) when there are gazillion SelectObject in the code ?

and finally, what is the preferred way to do it when I have multiple SelectObject in the same function? do I only need to keep the old handle for the first SelectObject and reset it at the end ?

C++
void f{)
{
 /// ... some code...
 HFONT oldFont = ::SelectObject( validHDC, validHFONT );
 /// ... do something ...
 ::SelectObject( validHDC, anotherHFONT );
 /// ... do something ...

 ::SelectObject( validHDC, thirdHFONT );
 /// ... do something ...

 ::SelectObject( validHDC, fourthHFONT );
 /// ... do something ...

 ::SelectObject( validHDC, oldFont);
}



Thanks.
Max.
Posted
Updated 19-Dec-11 8:03am
v3
Comments
Richard MacCutchan 19-Dec-11 15:23pm    
Looks OK.

1 solution

Short answer: Yes.
Longer answer: See the remarks section here[^]. GDI objects consume system resources so not returning them after use could result in your system being unable to satisfy a request, and your program could then produce the wrong results, or fail completely.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900