在c++中使用enable_shared_from_this时检查现有的shared_ptr?
除了捕获尝试在原始指针上调用shared_from_this()时抛出的bad_weak_ptr错误之外,是否有方法测试该对象是否正在被引用计数?
我有处理原始指针和共享指针的函数,并且我想确保在使用错误的指针时错误是明显的?我当然可以捕获错误,但我只是想知道是否有一种简单的方法来测试这种特殊情况?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于现有的有效对象或指向它的指针,对 std::enable_shared_from_this::shared_from_this() 的调用永远不会失败。编辑:...如果至少有一个
std::shared_ptr
实例,其中YourClass
是std::enable_shared_from_this
>。这是比第一个更严格的声明,如果被误解,我深表歉意。您可以通过仅创建类的
shared_ptr
实例来确保shared_from_this()
的有效性。除了捕获异常之外,无法检查YourClass
实例是否由shared_ptr
管理。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>
whereYourClass
isstd::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_ptr
instances of your classes. There is no way to check if aYourClass
instance is managed by ashared_ptr
, except of catching the exception.不要混合原始指针和托管指针。
Don't mix raw pointers and managed pointers.