Android本机强指针vs std :: shared_ptr [英] Android native strong pointer vs std::shared_ptr
问题描述
我指的是 Refbase.h , 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来说,您可能需要这样做: http://en.cppreference.com/w/cpp/memory/enable_shared_from_this
So while for shared_ptr you might need this: http://en.cppreference.com/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_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!