Click here to Skip to main content
13,248,112 members (35,866 online)
Rate this:
 
Please Sign up or sign in to vote.
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)
{
 /// ... some code...
 ::SelectObject( validHDC, validHFONT );
 /// ... do something ...
}


normally I'm used to seeing seomthing like
(2)
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 ?

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 19-Dec-11 8:37am
Maximilien84.4K
Updated 19-Dec-11 9:03am
v3
Comments
Richard MacCutchan 19-Dec-11 15:23pm
   
Looks OK.

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web04 | 2.8.171114.1 | Last Updated 19 Dec 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100