[smart_ptr] weak_ptr / shared_ptr interaction
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
At 1:55 PM +0200 7/3/09, Alexander Heinrich wrote:
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)
Both s1 and s2 should now have use_count of 2 at this point, since there are 2 shared_ptrs sharing ownership of the same pointee. The post-condition expression is correct; the value of r.use_count() was changed by the construction of the new shared_ptr.
participants (2)
-
Alexander Heinrich
-
Kim Barrett