Game Development Reference
In-Depth Information
to each other, neither one can ever have its reference count decremented. Basically,
because they point to each other, it ' s almost like two stubborn gentlemen saying,
No, sir, after you
and
Please, I insist
when trying to go through a single door
because they point to each other, they will never be destroyed.
The solution to this is usually some kind of
owned
pointer or
weak referenced
pointer, where one object is deemed the de facto owner and therefore won
t use the
multiply referenced shared_ptr mechanism. The weak_ptr template is used
exactly for this purpose:
'
class Jelly;
class PeanutButter
{
public:
shared_ptr<Jelly> m_pJelly;
˜
PeanutButter(void) { cout <<
PeanutButter destructor\n
;}
};
class Jelly
{
public:
weak_ptr<PeanutButter> m_pPeanutButter; // this is a weak pointer now!
˜
Jelly(void) { cout << “Jelly destructor\n”;}
};
void PleaseDontLeakMyMemory(void)
{
shared_ptr<PeanutButter> pPeanutButter(new PeanutButter);
shared_ptr<Jelly> pJelly(new Jelly);
pPeanutButter->m_pJelly = pJelly;
pJelly->m_pPeanutButter = pPeanutButter;
// No memory is leaked!
}
In this version of the code, PeanutButter is the owner, and Jelly has a weak ref-
erence back to PeanutButter . If you execute this code, both objects will be
destroyed, and you will see the destructor messages printed in the console.
The other gotcha is constructing two smart pointers to manage a single object:
int *z = new int;
shared_ptr<int> bad1(z);
shared_ptr<int> bad2(z);
Search WWH ::




Custom Search