Gamasutra: The Art & Business of Making Gamesspacer
View All     RSS
February 6, 2016
arrowPress Releases
February 6, 2016
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

Age of Learning, Inc.
Age of Learning, Inc. — Glendale, California, United States
[02.05.16]

Unity Technical Artist
Insomniac Games
Insomniac Games — Burbank, California, United States
[02.04.16]

UI Programmer
Rooster Teeth
Rooster Teeth — Austin, Texas, United States
[02.04.16]

Game Engineer
Vicarious Visions / Activision
Vicarious Visions / Activision — Albany, New York, United States
[02.04.16]

Software Engineer





Loading Comments

loader image