Reference counting of pointers to classes used across functions
Imagine that you have some dynamically allocated structure containing data, and you want to process it in different threads of execution. The code to do this is as follows:
#include <boost/thread.hpp>
#include <boost/bind.hpp>
void process1(const foo_class* p);
void process2(const foo_class* p);
void process3(const foo_class* p);
void foo1() {
while (foo_class* p = get_data()) // C way
{
// There will be too many threads soon, see
// recipe 'Parallel execution of different tasks'
// for a good way to avoid uncontrolled growth of threads
boost::thread(boost::bind(&process1, p))
.detach();
boost::thread(boost::bind(&process2, p))
.detach();
boost::thread(boost::bind(&process3, p))
.detach();
// delete p; Oops!!!!
}
}We cannot deallocate p at the end of the while loop because it still...