views:

263

answers:

2

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?

+2  A: 

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.

Billy ONeal
So we've got a reference incrementation operation only? Actually not surprising... yet there was something that was expensive in case of weak_ptr's -- any idea what that was? I assume that the opposite (construction of a weak_ptr from shared_ptr) should also be trivial...
Kornel Kisielewicz
@Kornel Kisielewicz: Previous comment deleted -- I thought it said "reference **implementation** only" at first LOL! My guess on the efficiency argument against `weak_ptr` is a comparison to builtin pointers rather than shared_ptrs (you can have a builtin pointer pointing to the same place as a shared_ptr, after all :) )
Billy ONeal
@Billy, yes, that might also be it. My second reaction after posting this question was that it might have something to do with threading, but it seems that weak and shared use the same reference counting structure, so there shouldn't be a difference.
Kornel Kisielewicz
@James -- so there is a performance drop -- because having a shared pointer, we would just dereference it, not copy. In case of weak_ptr we need that copy and ref increment to use it, and then decrement after it goes out of scope. So much for the 42 nanoseconds xP
Kornel Kisielewicz
A: 

42.6987 nanoseconds

Noah Roberts
Would've been better to just say over nine-thousand.
Wallacoloo
Since when upvoting useless answers on SO has become popular?
Kornel Kisielewicz