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.

JNo
  • 89
  • 12
  • 2
    Possibly the same: [How to check if weak_ptr is empty (non-assigned)?](https://stackoverflow.com/questions/45507041/how-to-check-if-weak-ptr-is-empty-non-assigned) – nada Jul 16 '19 at 11:38
  • 3
    weak_ptr::expired. https://en.cppreference.com/w/cpp/memory/weak_ptr/expired – AF_cpp Jul 16 '19 at 11:39
  • If you mean to use the [`assert` macro](https://en.cppreference.com/w/cpp/error/assert), 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. – Some programmer dude Jul 16 '19 at 11:41
  • @Someprogrammerdude i just use to for the development. – JNo Jul 16 '19 at 11:44
  • 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_ptr`s that it's associated with might hold a null pointer or it might not be associated with any `shared_ptr`s. 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. – Pete Becker Jul 16 '19 at 12:25
  • 1
    @AF_cpp can you post your comment as an answer so I can approve it? – JNo Jul 16 '19 at 12:36

1 Answers1

0

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

AF_cpp
  • 568
  • 5
  • 15