Android5.1 中智能指针涉及的文件如下:

system/core/include/utils/RefBase.h

system/core/libutils/RefBase.cpp

system/core/include/utils/StrongPointer.h

在学习Android的智能指针时,对于模板的使用不太清楚,于是我将sp类精简了一下,大概看一下在赋值和初始化的时候的函数调用关系:

 #include <iostream>

 using namespace std;

 template<typename T>
class sp {
public:
inline sp() {};
sp(T* other);
sp(const sp<T>& other);
template<typename U> sp(U* other);
template<typename U> sp(const sp<U>& other); ~sp(); sp& operator = (T* other);
sp& operator = (const sp<T>& other);
template<typename U> sp& operator = (const sp<U>& other);
template<typename U> sp& operator = (U* other);
}; template<typename T>
sp<T>::sp(T* other) {
cout << "enter sp(T* other) " << endl;
} template<typename T>
sp<T>::sp(const sp<T>& other) {
cout << "enter sp(const sp<T>& other) " << endl;
} template<typename T> template<typename U>
sp<T>::sp(U* other) {
cout << "enter sp(U *other) " << endl;
} template<typename T> template<typename U>
sp<T>::sp(const sp<U>& other) {
cout << "sp(const sp<U& other>)" << endl;
} template<typename T>
sp<T>::~sp() {
} template<typename T>
sp<T>& sp<T>::operator =(T* other) {
cout << "enter operator =(T* other) " << endl;
return *this;
} template<typename T>
sp<T>& sp<T>::operator =(const sp<T>& other) {
cout << "enter operator = (const sp<T>& other)" << endl;
return *this;
} template<typename T> template<typename U>
sp<T>& sp<T>::operator =(const sp<U>& other) {
cout << "operator = (const sp<U>& other)" << endl;
return *this;
} template<typename T> template<typename U>
sp<T>& sp<T>::operator =(U* other) {
cout << "operator = (U* other)" << endl;
return *this;
} class Peng{
}; class Dong {
}; int main(int argc, const char *argv[])
{
Peng *p = new Peng();
Dong *d = new Dong(); cout << "---- sp<Peng> q = p ----" << endl;
sp<Peng> q = p; cout << "\n---- sp<Peng> r(p) ----" << endl;
sp<Peng> r(p); cout << "\n---- sp<Peng> b(r) ----" << endl;
sp<Peng> b(r); cout << "\n---- sp<Peng> t; ----" << endl;
sp<Peng> t;
cout << "\n---- t = p ----" << endl;
t = p; cout << "\n---- sp<Peng> a; ----" << endl;
sp<Peng> a;
cout << "\n---- a = t ----" << endl;
a = t; Dong *c = new Dong();
cout << "\n---- sp<Dong> e = c ----" << endl;
sp<Dong> e = c;
cout << "\n---- a = e ----" << endl;
a = e;
cout << "\n---- a = c ----" << endl;
a = c; cout << "\n---- sp<Dong> e1(e) ----" << endl;
sp<Peng> e1(e); cout << endl << endl;
return ;
}

下面是在PC机上的运行结果:

pengdl@pengdl-HP:~/work/study/c++$ ./a.out
---- sp<Peng> q = p ----
enter sp(T* other) ---- sp<Peng> r(p) ----
enter sp(T* other) ---- sp<Peng> b(r) ----
enter sp(const sp<T>& other) ---- sp<Peng> t; ---- ---- t = p ----
enter operator =(T* other) ---- sp<Peng> a; ---- ---- a = t ----
enter operator = (const sp<T>& other) ---- sp<Dong> e = c ----
enter sp(T* other) ---- a = e ----
operator = (const sp<U>& other) ---- a = c ----
operator = (U* other) ---- sp<Dong> e1(e) ----
sp(const sp<U& other>)

完。

05-11 19:32