I'm currently designing a object structure for a game, and the most natural organization in my case became a tree. Being a great fan of smart pointers I use shared_ptr
's exclusively. However, in this case, the children in the tree will need access to it's parent (example -- beings on map need to be able to access map data -- ergo the data of their parents.
The direction of owning is of course that a map owns it's beings, so holds shared pointers to them. To access the map data from within a being we however need a pointer to the parent -- the smart pointer way is to use a reference, ergo a weak_ptr
.
However, I once read that locking a weak_ptr
is a expensive operation -- maybe that's not true anymore -- but considering that the weak_ptr
will be locked very often, I'm concerned that this design is doomed with poor performance.
Hence the question:
What is the performance penalty of locking a weak_ptr? How significant is it?
The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.
Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe.
You can implement weak_ptr which works correctly with unique_ptr but only on the same thread - lock method will be unnecessary in this case.
std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.
From the Boost 1.42 source code (<boost/shared_ptr/weak_ptr.hpp>
line 155):
shared_ptr<T> lock() const // never throws { return shared_ptr<element_type>( *this, boost::detail::sp_nothrow_tag() ); }
ergo, James McNellis's comment is correct; it's the cost of copy-constructing a shared_ptr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With