1

The use of assert for checking whether a shared_ptr is not nullPtr is explained in c++ how to assert that all std::shared_ptr in a vector are referring to something but I don't find a decent way to check the same for a weak_ptr. I try to avoid converting it to shared_ptr so pls let me know your other solutions.

6
  • 2
    Possibly the same: How to check if weak_ptr is empty (non-assigned)? Commented Jul 16, 2019 at 11:38
  • 3
    weak_ptr::expired. en.cppreference.com/w/cpp/memory/weak_ptr/expired Commented Jul 16, 2019 at 11:39
  • If you mean to use the assert macro, note that it's "disabled" (expands to nothing) on typical release builds. It will also "crash" your program if it fails. Therefore it shouldn't really be used for run-time check in production builds. Commented Jul 16, 2019 at 11:41
  • 2
    Be careful: a shared_ptr cannot be nullPtr (if I'm reading the intent of that name correctly). It can hold a null pointer. With a weak_ptr there are two possible ways that it might not refer to actual memory: the shared_ptrs that it's associated with might hold a null pointer or it might not be associated with any shared_ptrs. So there isn't anything that's "the same", but two things that are similar. You'll have to say which one you mean, or you'll get guesses instead of actual answers. Commented Jul 16, 2019 at 12:25
  • 1
    @AF_cpp can you post your comment as an answer so I can approve it? Commented Jul 16, 2019 at 12:36

1 Answer 1

1

If you want to check whether the referenced model has already been deleted or whether the weak reference is empty -> use std::weak_ptr::expired().

reference documentation: https://en.cppreference.com/w/cpp/memory/weak_ptr/expired

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.