0

Apologies if this has been answered before, I haven't been able to find an answer.

I'm doing some painting in my Win32 application, and have quite a few scenarios where I need to paint an object (e.g. a rectangle) only once. The way I'm currently creating brushes for this is as follows:

HBRUSH sampleBrush = CreateSolidBrush(RGB(1, 119, 158));
SelectObject(myDC, sampleBrush);
// Do some painting on DC using brush
DeleteObject(sampleBrush);

Create brush, store handle, select into DC, use brush, release memory.

However, if I were to do the following instead:

SelectObject(myDC, CreateSolidBrush(RGB(1, 119, 158)));

Would there be any memory management required since I'm not storing a handle to the brush I create? And if so, how would I release the memory?

BeneGal
  • 180
  • 1
  • 11

1 Answers1

3

The function CreateSolidBrush cannot know how you are using it. It can't know that you aren't storing the handle and therefore perform some automatic clean up. Since the documentation of CreateSolidBrush specifies that you should call DeleteObject with the returned handle, you should make sure you abide by those requirements.

If you don't store the handle, then you lose access to it and can't ensure that the object is destroyed.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • That makes sense, thanks for clearing it up. I don't have enough reputation to upvote you but I would if I could! – BeneGal May 01 '13 at 11:47
  • 1
    And also select the brush (that you selected out) back into the DC (when you select your brush out) otherwise that may leak too. – Deanna May 01 '13 at 12:51