Is there a way to distinguish between an assigned (possibly expired) weak_ptr and a non-assigned one.
weak_ptr w1;
weak_ptr w2 = ...;
You could try to create a shared pointer that accepts a weak pointer as a parameter and raises a std::bad_weak_ptr exception if a weak pointer is expired (or not assigned as in your case):
#include
#include
int main(){
// with an assigned pointer
std::shared_ptr p1(new int(42));
std::weak_ptr w1(p1);
try {
std::shared_ptr p2(w1);
}
catch (const std::bad_weak_ptr& e) {
std::cout << e.what() << '\n';
}
// with a non assigned pointer
std::shared_ptr p2(new int(42));
std::weak_ptr w2;
try {
std::shared_ptr p2(w2); // raises an exception
}
catch (const std::bad_weak_ptr& e) {
std::cout << "Ptr 2: " << e.what() << '\n';
}
}