Sponsored By

Common pitfalls when using vectors -- releasing references.

Brad Wardell, Blogger

December 2, 2009

2 Min Read

Often times it's tempting to simply turn a member variable to NULL when you're ready to use it or add a reference.  

However, doing so can result in memory leaks.

Here's a quick suggestion:

GOOD:

VOID CMyClass::SetVertexBuffer (PVertexBufferWrapper pVBuffer )

{

//Release existing buffer

SAFE_RELEASE( m_pVBuffer );

 

// setthe member pointer to new pointer

               m_pVBuffer = pVBuffer;

 

// adda ref

if (pVBuffer )

pVBuffer->AddRef ();

}

The above will release anyexisting buffer ptr first.  This requires the member variable to be initializedto NULL.  You should get in the habit of initializing values anyways, asdoing so helps eliminate many “release-only” bugs.

 

BAD:

 

VOID CMyClass::SetVertexBuffer (PVertexBufferWrapper pVBuffer )

{

// setthe member pointer to new pointer

               m_pVBuffer = pVBuffer;

 

// adda ref

if (pVBuffer )

pVBuffer->AddRef ();

}

 

The above code will not release areference if m_pVBuffer already had a pointer to a different vertex buffer whenthis function is called.  This causes memory leaks.

 

Read more about:

2009Blogs

About the Author(s)

Brad Wardell

Blogger

Brad Wardell is currently the CEO and president of Stardock Corporation, one of the leaders in Windows customization software with massively popular software products like Windowblinds and MyColors. Recently, Wardell successfully steered the company into the PC gaming space, developing and publishing smash-hit titles such as the award-winning Galactic Civilizations series and Sins of a Solar Empire. Wardell’s passion for gaming excellence has inspired the company to expand even further to develop a one-stop-shop platform for PC game downloads called Impulse, which launches Q2 of 2008. Wardell resides in Plymouth, Michigan and can bench 350 pounds. Additionally, he can leap tall buildings in a single bound.

Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like