Aside from catching the bad_weak_ptr error thrown when trying to call shared_from_this() on a pointer that is a raw pointer, is there a way of testing whether or not the object is being reference counted?
I have functions that deal with the raw pointer and shared pointer and I want to be sure that the error is obvious when using the wrong one? I can of course just catch the error, but I just wondered if there’s an easy way of testing for this particular case?
A call to
std::enable_shared_from_this<T>::shared_from_this()will never fail for an existing valid object, or pointer to it. EDIT: … if there is at least one instance ofstd::shared_ptr<YourClass>whereYourClassisstd::enable_shared_from_this<YourClass>. This is a stricter statement than the first one and I apologize if it was misunderstood.You assure the validity of
shared_from_this()by creating onlyshared_ptrinstances of your classes. There is no way to check if aYourClassinstance is managed by ashared_ptr, except of catching the exception.