Gamasutra: The Art & Business of Making Gamesspacer
View All     RSS
December 22, 2014
arrowPress Releases
December 22, 2014
PR Newswire
View All
View All     Submit Event






If you enjoy reading this site, you might also want to check out these UBM Tech sites:


 
Safely releasing references in C++
by Brad Wardell on 12/02/09 07:56:00 pm   Expert Blogs

2 comments Share on Twitter Share on Facebook    RSS

The following blog post, unless otherwise noted, was written by a member of Gamasutra’s community.
The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company.

 

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.

 


Related Jobs

Cignition
Cignition — Palo Alto, California, United States
[12.22.14]

Game Programmer
En Masse Entertainment
En Masse Entertainment — Seattle, Washington, United States
[12.19.14]

Network Engineer
Sucker Punch Productions
Sucker Punch Productions — Bellevue, Washington, United States
[12.19.14]

IT Administrator
Sucker Punch Productions
Sucker Punch Productions — Bellevue, Washington, United States
[12.19.14]

IT Administrator





Loading Comments

loader image