cebola
cebola

Reputation: 194

Why weak_ptr::use_count may return a different count to shared_ptr::use_count?

The cppreference.com's entry on weak_ptr::use_count includes the caveat:

The usage and behavior of this function are similar to std::shared_ptr::use_count, but it returns a different count.

Since it's supposed to count how many shared_ptr instances share ownership of the pointer, under which circumstances could it return a different count?

Upvotes: 4

Views: 143

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123228

The text in the c++ standard draft is:

long use_count() const noexcept;

Returns: 0 if *this is empty; otherwise, the number of shared_ptr instances that share ownership with *this.

I suppose, what the note tries to say is that weak_ptr::use_count cannot simply return the value of the std::shared_ptrs count from which it was created. When all shared pointers are gone, std::weak_ptr::use_count can still be called and returns 0.

Don't forget that cppreference is a wiki, it is community curated. Usually it is rather close to the text in the standard. I didn't find anything similar to this note in the standard though.

Upvotes: 3

Related Questions