I am making extensive use of boost:shared_ptr in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr. Unf
With C++11 shared_ptr and enable_shared_from_this is now in the standard library. The latter is, as the name suggests, for this case exactly.
http://en.cppreference.com/w/cpp/memory/shared_ptr
http://en.cppreference.com/w/cpp/memory/enable_shared_from_this
Example bases on that in the links above:
struct Good: std::enable_shared_from_this{
std::shared_ptr getptr() {
return shared_from_this();
}
};
use:
std::shared_ptr gp1(new Good);
std::shared_ptr gp2 = gp1->getptr();
std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';