Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the performance penalty of weak_ptr?

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?

like image 703
Kornel Kisielewicz Avatar asked Apr 30 '10 22:04

Kornel Kisielewicz


People also ask

What is the difference between shared_ptr and weak_ptr?

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.

Is weak_ptr lock thread safe?

Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe.

Can a weak_ptr point to a Unique_ptr?

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.

What is weak_ptr?

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.


1 Answers

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.

like image 139
Billy ONeal Avatar answered Oct 13 '22 10:10

Billy ONeal