Gamasutra is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Gamasutra: The Art & Business of Making Gamesspacer
View All     RSS
July 15, 2019
arrowPress Releases







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    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

DMG Entertainment
DMG Entertainment — Beverly Hills, California, United States
[07.12.19]

Game Engineer
Giant Army
Giant Army — Remote, Washington, United States
[07.11.19]

Graphics Developer for Universe Sandbox
Build A Rocket Boy Games
Build A Rocket Boy Games — Edinburgh, Scotland, United Kingdom
[07.11.19]

Senior Animation Programmer
Build A Rocket Boy Games
Build A Rocket Boy Games — Edinburgh, Scotland, United Kingdom
[07.11.19]

Gameplay Networking Programmer - All Levels





Loading Comments

loader image