[c++0x] shared_ptr get() and use_count() inconsistency

Rodolfo Lima rodolfo@rodsoft.org
Thu Jun 5 04:43:00 GMT 2008


Hi, I've been playing with shared_ptr and its aliasing constructor and 
the following code doesn't work as expected:

int main()
{
     std::shared_ptr<int> aux;
     int i;
     std::shared_ptr<int> aux2(aux, &i);
     assert(aux2.use_count() == 0);
     assert((bool)aux2, false); // assert failure here
     assert(aux2.get() == NULL); // assert failure here
}

I know there's no C++0x standard yet, blah blah blah, but in current 
libstdc++ implementation shared_ptr's get returns something different 
than NULL even when use_count()==0.

The current standard draft says that use_count() should return 0 if the 
shared_ptr is empty, and get() should return NULL if the shared_ptr is 
also empty.

The current implementation simply returns the stored pointer, whether 
use_count() is 0 or not.

I've attached a patch with two possible solutions. The first 
(shared_ptr.diff) just checks if use_count()==0 before returning the 
stored pointer, if it is, returns NULL. Is also changes operator-> and 
operator* to use get() with the correct semantics. This problem is that 
this solution incurs some overhead, with an addition of an comparison.

The second solution (shared_ptr_fast.diff) sets the stored pointer to 
NULL in the aliasing ctor if the shared_ptr to be aliased has 
use_count()==0. AFAIK, the semantics is the same of the last solution, 
but this one is faster because the comparison is done just one time. I 
didn't check if this has bad side effects I didn't think of.

Regards,
Rodolfo Lima.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: shared_ptr.diff
URL: <http://gcc.gnu.org/pipermail/libstdc++/attachments/20080605/2a91316c/attachment.ksh>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: shared_ptr_fast.diff
URL: <http://gcc.gnu.org/pipermail/libstdc++/attachments/20080605/2a91316c/attachment-0001.ksh>


More information about the Libstdc++ mailing list