Boost logo

Boost Users :

Subject: [Boost-users] [smart_ptr] weak_ptr / shared_ptr interaction
From: Alexander Heinrich (alexander.tobias.heinrich_at_[hidden])
Date: 2009-07-03 07:55:10


Hi @ boost-users.
The documentation of shared_ptr states the following:
<quote>
template<class Y> explicit shared_ptr(weak_ptr<Y> const & r);

Effects: Constructs a shared_ptr that shares ownership with r and stores a
copy of the pointer stored in r.

Postconditions: use_count() == r.use_count().
</quote>
Now I experienced some odd behavior with the following piece of code:
<code>
boost::shared_ptr<int> s1(new int(42)); // use_count == 1
boost::weak_ptr<int> w(s1); // use_count == 1
boost::shared_ptr<int> s2(w); // use_count == 2 (expected use_count == 1)
boost::shared_ptr<int> s3 = s2; // use_count == 3 (not sure what to expect
here...)
</code>
1) According to the documentation use_count should still be 1 after
instantiating s2, but it is 2. Or did I misinterpret the docs?
2) Independent of whether instantiating s2 increments the use_count or not,
I am unsure if assigning (or copying) a shared_ptr that was constructed from
a weak_ptr should increment the use_count (see s3).
I'd appreciate any comments on this.
Best regards,
Alexander



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net