I\'ve been thinking about using shared pointers, and I know how to implement one myself--Don\'t want to do it, so I\'m trying std::tr1::shared_ptr,and I have co
Are there any pitfalls for using the
std::tr1::shared_ptr?
Yes, If you create cycles in your shared memory pointers, then the memory being managed by the smart pointer will not be recycled when the last pointer goes out of scope because there are still references to the pointer (i.e., the cycles cause the reference count to not go down to zero).
For instance:
struct A
{
std::shared_ptr ptr;
};
std::shared_ptr shrd_ptr_1 = std::make_shared(A());
std::shared_ptr shrd_ptr_2 = std::make_shared(A());
shrd_ptr_1->ptr = shrd_ptr_2;
shrd_ptr_2->ptr = shrd_ptr_1;
Now, even if shrd_ptr_1 and shrd_ptr_2 go out of scope, the memory they are managing is not reclaimed because the ptr member of each are pointing to each other. While this is a very naive example of such a memory cycle, it can, if you use these types of pointers without any discipline, occur in a much more nefarious and hard-to-track fashion. For instance, I could see where trying to implement a circular linked-list where each next pointer is a std::shared_ptr, if you're not too careful, could result in problems.