My Message close
GAME JOBS
Latest Jobs
spacer View All     Post a Job     RSS spacer
 
May 21, 2013
 
Blizzard Entertainment
Senior Software Engineer, User Interface
 
Blizzard Entertainment
Senior Technical Artist
 
Blizzard Entertainment
3D Environment Artist, Senior
 
Blizzard Entertainment
Dungeon Texture Artist
 
Blizzard Entertainment
3D Character Artist, Lead
 
Hidden Variable Studios
Senior Designer
spacer
Blogs

  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 was, unless otherwise noted, independently written by a member of Gamasutra's game development community. The thoughts and opinions expressed here are not necessarily those of Gamasutra or its parent company.

Want to write your own blog post on Gamasutra? It's easy! Click here to get started. Your post could be featured on Gamasutra's home page, right alongside our award-winning articles and news stories.
 

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.

 

 
 
Comments

Chris Howe
profile image
Manually managing reference counts can also lead to memory leaks. Better to use smart pointers that will handle the reference counting for you.

Andrew Green
profile image
Always add ref *then* release refs:



if (pVBuffer)

pVBuffer->AddRef();

SAFE_RELEASE(m_pVBuffer);

m_pVBuffer = pVBuffer;



*or*

bail before manipulating refcounts if m_PVBuffer==pVBuffer.


none
 
Comment:
 




 
UBM Tech