Aside from catching the bad_weak_ptr error 开发者_如何学Gothrown 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 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.
Don't mix raw pointers and managed pointers.
精彩评论