Android 智能指针(1):hello world 篇
Android Native 层的稳定性,离不开智能指针。所谓入乡随俗,仅知道C++ 通用智能指针,还是不够充分的。为了方便学习Android 智能指针,只能抠下来。。。不然太依赖手机设备了,另外也有诸多不便。
指针库代码均来自于cs.android.com.
以下是基于Raspberry Pi5 上的测试。
一,Hello World
头文件TestDataType.h
#pragma once
#include <utils/RefBase.h>
#include <string>
#include <iostream>
using namespace android;
class TestSP:public RefBase {
private:
std::string mName;
public:
TestSP()=default;
TestSP(std::string &name):mName(std::move(name)){
std::cout<<"TestSP Construct: "<<mName<<std::endl;
}
~TestSP(){
std::cout<<"Bye,TestSP Destructor...\n";
}
};
测试代码:
#include<iostream>
#include<cstring>
#include <TestDataType.h>
using namespace std;
void testSpCreate(){
string name(">>>HelloWorld<<<");
sp<TestSP> ptr = sp<TestSP>::make(name);
sp<TestSP> ptr2 = ptr;
std::cout<<"refrence count:"<<ptr2->getStrongCount()<<std::endl;
}
int main() {
testSpCreate();
cout<<"exit...\n";
return 0;
}
运行结果:
TestSP Construct: >>>HelloWorld<<<
refrence count:2
Bye,TestSP Destructor...
exit...
二, 解读
使用Android智能指针和C++通用智能指针不一样. Android智能指针使用的对象有限制的,不是所有的对象都可以使用。如果你想使用Android智能指针管理你的对象,需要对象继承RefBase
。否则会报错。这一点和C++通用智能指针不一样。
常见的创建方式有两种
方式1:sp<TestSp> ptr= new TestSP(..);
方式2:sp<TestSp> ptr= sp<TestSp>::make(...);
template<typename T>
class sp {
public:
inline constexpr sp() : m_ptr(nullptr) { }
//skip
template <typename... Args>
static inline sp<T> make(Args&&... args);
sp(T* other); // NOLINT(implicit)
template <typename U>
sp(U* other); // NOLINT(implicit)
sp& operator=(T* other);
template <typename U>
sp& operator=(U* other);
// Reset
void clear();
//skip
}
整个Android Native 层代码使用的基本都是第一种方式,new的方式。
对比C++ 通用方式 ,相对常用的方式:
template< class Y >
explicit shared_ptr( Y* ptr );
template< class Y, class Deleter >
shared_ptr( Y* ptr, Deleter d );
template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );
相对C++通用智能指针,Android 的指针就简单些,不能自定义deleter,不能自定义allocator。
三, sp常用的方法
sp方法不多,相对常用的是get(),和clear().get()
:获取原始指针clear()
:释放sp的原始指针。
后面再详细记录andorid的强指针sp以及弱指针wp...