Gamasutra: The Art & Business of Making Gamesspacer
View All     RSS
September 21, 2014
arrowPress Releases
September 21, 2014
PR Newswire
View All





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

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

Infinity Ward / Activision
Infinity Ward / Activision — Woodland Hills, California, United States
[09.20.14]

Senior AI Engineer
Infinity Ward / Activision
Infinity Ward / Activision — Woodland Hills, California, United States
[09.20.14]

Lead Tools Engineer - Infinity Ward
Insomniac Games
Insomniac Games — Burbank , California, United States
[09.19.14]

Senior Engine Programmer
Nexon America, Inc.
Nexon America, Inc. — El Segundo , California, United States
[09.19.14]

Front-End Developer






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: