For example:
std::weak_ptr<int> wp1(std::make_shared<int>());
std::weak_ptr<int> wp2;
assert(PointsToValidOrExpiredObject(wp1));
assert(!PointsToValidOrExpiredObject(wp2));
Is such a function possible?
Use case: A class's constructor takes std::weak_ptr<Foo> as a dependency. Passing an expired object is ok (might happen in certain workflows), but passing null means the programmer forget something. I'd like to test for this as part of the constructor's parameter validation.
std::weak_ptr::owner_beforecan distinguish between weak pointers that are empty and expired. You can therefore implementPointsToValidOrExpiredObjectas:Demo.
Regarding the original uncertainty I had about an expired
weak_ptrstill maintaining ownership: I'm now certain that the general library-wide thread-safety requirements mandate that an expiredweak_ptrcontinues to have the same ownership. Otherwise, destroying the last remainingshared_ptrin thread A would have to observably modify the state of one/some/allweak_ptrs that share ownership with theshared_ptrin question. If thread B was simultaneously examining the state of such aweak_ptrthen you would have a data race introduced by the library implementation which is forbidden in general.