作者gn00618777 (非常念舊)
看板AndroidDev
標題[問題] Android 的智能指標 sp
時間Sun Apr 24 23:18:17 2016
不知道有沒有人瞭解 Android 的 class sp?
在源碼中我常看到下面用法
sp <Camera> c = new Camera(int)
new 在 c++中就是配置記憶體然後回傳記憶體位址,但 c 又是一個物件。事實上,我根
本搞不清楚 android 的這個 c 代表的是甚麼。一開始我以為他是一個指標,去接new
出來的。但好像不是這麼回事,因為我寫了一個小程式去試
#include<iostream>
using namespace std;
template<typename T>
class sp{
public:
sp(T *other){
cout<<"This is the first constructor"<<endl;
}
sp(const sp<T>& other){}
};
class myClass{
public:
myClass():a(0){}
int getA(){
return a;
}
private:
int a;
};
int main(){
sp<myClass> c = new myClass();
cout<<c->sp()<<endl;
}
出來的訊息意思是說 c 是一個物件,不是一個指標~
[Error] base operand of '->' has non-pointer type 'sp<myClass>'
應該是 android 的 class sp 有寫些動作.....,小弟底子差,看了幾天也問了板友只
知道
sp<myClass> c = new myClass()
這個用法會用到 c++ 的 copy initialization,以及我知道他會 call 到 class sp 內
的 sp(T *other) 建構子, 我不知道這個 c 代表甚麼?
sp<myClass> c = new myClass() 這個式子
會動用到 class sp 內的哪一個 operater overload 還是 不會?
~"~
希望能從各位牛人汲取到一點建議
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 58.115.110.72
※ 文章網址: https://www.ptt.cc/bbs/AndroidDev/M.1461511100.A.547.html
推 rexx: kheresy.wordpress.com/2012/03/03/c11_smartpointer_p1/ 04/24 23:56
推 rexx: c是一個物件 但他有寫operator->() 所以可以用pointer的寫法 04/25 00:00
→ rexx: c->xxx這樣 感覺上直接當做pointer在用 04/25 00:01
→ rexx: 有興趣可以去看他source code 04/25 00:01
→ rexx: include/utils/StrongPointer.h 04/25 00:02
→ cha122977: sp<Camera>可以直接當成Camera*來用 04/25 02:03
→ cha122977: 用sp包他是為了自己管理delete時機(ARC) 04/25 02:04
→ gn00618777: 看到了一些關鍵,有時間消化完再來分享.. 04/25 23:04