Dan
Dan

Reputation: 35503

check existing shared_ptr when using enable_shared_from_this in c++?

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?

Upvotes: 0

Views: 792

Answers (2)

Paul Michalik
Paul Michalik

Reputation: 4381

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 of std::shared_ptr<YourClass> where YourClass is std::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 only shared_ptr instances of your classes. There is no way to check if a YourClass instance is managed by a shared_ptr, except of catching the exception.

Upvotes: 2

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145457

Don't mix raw pointers and managed pointers.

Upvotes: 1

Related Questions