Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top