I have found a similar question but my example is slightly different.
Here is a very simple example:
int main()
{
auto sp = std::make_shared<T>();
std::weak_ptr<T> wp = sp;
sp.reset();
assert(wp.expired());
}
Is it guaranteed that in the above case weak_ptr is always expired after shared_ptr reset ?
Yes, this is guaranteed. Calling
sp.reset();
is the equivalent of
shared_ptr().swap(*this)
Which means that sp
is now back to a default constructed state. If we look at use_count
in the standard we have
Returns: the number of
shared_ptr
objects,*this
included, that share ownership with*this
, or0
when*this
is empty.
And since it is empty, use_count
is 0
and expried
will be true as expried
Checks whether the managed object has already been deleted. Equivalent to
use_count() == 0
.