Game Development Reference
In-Depth Information
Be Careful Using Threads and Sharing Memory
Don
t ignore multithreaded access to shared memory blocks. You might think
that the chances of two threads accessing the shared data are exceedingly low
and convince yourself that you don
'
'
t need to go to the trouble of adding
multithreaded protection. You
'
d be wrong every time.
There are a couple of safety tips with smart pointers.
n You can
t have two different objects manage smart pointers for each other.
n When you create a smart pointer, you have to make sure it is created straight
from a raw pointer new operator.
'
I
ll show you examples of each of these abuses. If two objects have smart pointers to
each other, neither one will ever be destroyed. It may take your brain a moment to
get this, since each one has a reference to the other.
'
class Jelly;
class PeanutButter
{
public:
shared_ptr<Jelly> m_pJelly;
˜
PeanutButter(void) { cout <<
PeanutButter destructor\n
;}
};
class Jelly
{
public:
shared_ptr<PeanutButter> m_pPeanutButter;
˜
Jelly(void) { cout <<
Jelly destructor\n
;}
};
void PleaseLeakMyMemory(void)
{
shared_ptr<PeanutButter> pPeanutButter(new PeanutButter);
shared_ptr<Jelly> pJelly(new Jelly);
pPeanutButter->m_pJelly = pJelly;
pJelly->m_pPeanutButter = pPeanutButter;
// Both objects are leaked here
.
}
If you copied this code into the compiler, you would never see the messages printed
out in the destructors. Following the code, you
ll find that Jelly has a reference to
PeanutButter and PeanutButter has a reference to Jelly . Since they both point
'
 
Search WWH ::




Custom Search