Game Development Reference
In-Depth Information
C++
s shared_ptr
If you think calling AddRef() and Release() all over the place might be a serious
pain in the rear, you
'
s really easy to forget an AddRef() or a Release()
call, and your memory leak will be almost impossible to find. It turns out that there
are plenty of C++ templates out there that implement reference counting in a way
that handles the counter manipulation automatically. One of the best examples is
the shared_ptr template class in the standard TR1 C++ library.
Here
'
re right. It
'
'
s an example of how to use this template:
#include <memory>
using std::tr1::shared_ptr;
class IPrintable
{
public:
virtual void VPrint()=0;
};
class CPrintable : public IPrintable
{
char *m_Name;
public:
CPrintable(char *name) { m_Name = name; printf(
create %s\n
,m_Name); }
virtual
CPrintable()
{ printf(
delete %s\n
,m_Name); }
˜
void VPrint()
{ printf(
print %s\n
,m_Name); }
};
shared_ptr<CPrintable> CreateAnObject(char *name)
{
return shared_ptr<CPrintable>(new CPrintable(name));
}
void ProcessObject(shared_ptr<CPrintable> o)
{
printf(“(print from a function) ”);
o->VPrint();
}
void TestSharedPointers(void)
{
shared_ptr<CPrintable> ptr1(new CPrintable(
1
)); // create object 1
shared_ptr<CPrintable> ptr2(new CPrintable(
2
)); // create object 2
 
 
 
Search WWH ::




Custom Search