Game Development Reference
In-Depth Information
ptr1 = ptr2;
// destroy object 1
ptr2 = CreateAnObject(
3
); // used as a return value
ProcessObject(ptr1);
// call a function
// BAD USAGE EXAMPLES....
//
CPrintable o1(
bad
);
//ptr1 = &o1;
// Syntax error! It
'
s on the stack
.
//
CPrintable *o2 = new CPrintable(
bad2
);
//ptr1 = o2;
// Syntax error! Use the next line to do this
ptr1 = shared_ptr<CPrintable>(o2);
// You can even use shared_ptr on ints!
shared_ptr<int> a(new int);
shared_ptr<int> b(new int);
*a = 5;
*b = 6;
const int *q = a.get(); // use this for reading in multithreaded code
// this is especially cool - you can also use it in lists.
std::list< shared_ptr<int> > intList;
std::list< shared_ptr<IPrintable> > printableList;
for (int i=0; i<100; ++i)
{
intList.push_back(shared_ptr<int>(new int(rand())));
printableList.push_back(shared_ptr<IPrintable>(new CPrintable(
list
)));
}
// No leaks!!!! Isn
'
t that cool...
}
The template classes use overloaded assignment operators and copy operators to keep
track of how many references point to the allocated data. As long as the
shared_ptr object is in scope and you behave yourself by avoiding the bad usage
cases, you won
t have to worry about objects getting
destroyed while you are still referencing them from somewhere else.
This smart pointer even works in multithreaded environments, as long as you follow
a few rules. First, don
'
t leak memory, and you won
'
t write directly to the data. You can access the data through
const operations such as the .get() method. As you can also see, the template
works fine even if it is inside an STL container such as std::list .
'
Search WWH ::




Custom Search