我指的是 Refbase.h , Refbase.cpp 和 StrongPointer.h
在Android强指针实现中,任何基于强指针的对象都必须继承refbase即
In the Android implementation of strong pointer, any strong-pointer based object must inherit refbase i.e.
sp<TheClass> theObj // TheClass must inherit from class RefBase此要求可以在sp方法之一的代码中看到:
This requirement can be seen in the code for one of sp's methods:
template<typename T> sp<T>& sp<T>::operator =(T* other) { if (other != NULL) { other->incStrong(this); } if (mPtr != NULL) { mPtr->decStrong(this); } mPtr = other; return *this; }为了使对incStrong或decStrong的调用不会失败. . . other和mPtr必须继承了RefBase
In order for call to incStrong or decStrong to not fail . . . other and mPtr must have inherited RefBase
问题
为什么要实现sp,使得要求管理的obj是RefBase的子代?甚至没有办法在编译时甚至运行时强制执行此要求. (也许if(type()...)
Why is sp implemented such that the obj that it's managing is required to be a child of RefBase? There's not even a way to enforce this requirement at compile-time or even runtime. (Well maybe if(type()...)
标准库没有这样的要求
... 经过进一步思考,是否可以提供灵活性的答案? 如果是,那么如何提供灵活性?
... Upon further thought, is the answer that this provides flexibility? If yes, how does this provide flexibility?
推荐答案它自动允许您从任何实现RefBase的对象中创建sp,而对于共享指针,您可以在尝试将原始指针包装到共享对象中时大开眼界.
It automatically allows you to create sp from any object implementing RefBase, while for shared pointer you can shoot yourself in the foot while trying to wrap raw pointer into shared one.
因此,对于shared_ptr来说,您可能需要这样做: en.cppreference/w/cpp/memory/enable_shared_from_this
So while for shared_ptr you might need this: en.cppreference/w/cpp/memory/enable_shared_from_this
对于sp,您几乎可以安全地将原始指针传递给sp构造器.
for sp you can almost safely pass raw pointer to sp contructor.
更多推荐
Android本机强指针vs std :: shared
发布评论