Is there a way to distinguish between an assigned (possibly expired) weak_ptr and a non-assigned one.
weak_ptr w1;
weak_ptr w2 = ...;
Using std::weak_ptr::expired()
#include
#include
//declare a weak pointer
std::weak_ptr gw;
void f()
{
//check if expired
if (!gw.expired()) {
std::cout << "pointer is valid\n";
}
else {
std::cout << "pointer is expired\n";
}
}
int main()
{
f();
{
auto cre = std::make_shared(89);
gw = cre;
f();
}
f();
}
Output
pointer is expired
pointer is valid
pointer is expired
Program ended with exit code: 0