阅读obs代码时候遇到指针的代码,就展开学习一下。
/*自定义删除器*/
static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
profiler_name_store_free(store);
};
using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
decltype(ProfilerNameStoreRelease)>;
ProfilerNameStore CreateNameStore()
{
return ProfilerNameStore{profiler_name_store_create(),
ProfilerNameStoreRelease};
}
新的标准库提供了俩种智能指针类型类管理动态对象。
shared_ptr:允许多个指针指向同一个对象。
unique_ptr: 独占所有指向的对象。
- 首先讲unique_ptr
一个unique_ptr拥有它所指向的对象。某个时刻智能有一个unique_ptr指向一个给定对象。当unique_ptr被销毁时,它所指向的对象也被销毁。
unique_ptr的基本操作有:
//智能指针的创建
unique_ptr<T> p1; //创建空智能指针
p1.reset(new int(3)); //绑定动态对象
unique_ptr<int> p2(new int(4));//p2指向一个值为4的int
unique_ptr<objT,delfcn> p(new objT,fcn); //创建空 unique_ptr,执行类型为objT 的对象,用类型为 delfcn 的对象 fcn 来替代默认的删除器 delete
//所有权的变化
int *p_i = u_i2.release(); //释放所有权
unique_ptr<string> u_s(new string("abc"));
unique_ptr<string> u_s2 = std::move(u_s); //所有权转移(通过移动语义),u_s所有权转移后,变成“空指针”
u_s2.reset(u_s.release()); //所有权转移
u_s2=nullptr;//显式销毁所指对象,同时智能指针变为空指针。与u_s2.reset()等价
//错误
unique_ptr<string> p2(p1);//错误,不支持拷贝
p2 = p1;//不支持赋值
示例:
template<typename T>
struct Node{
T data;
unique_ptr<Node<T>> next;
~Node(){
cout<<"~Node";
}
};
template<typename T>
class Link{
public:
Node<T> head;
public:
void front(const T& data){
auto node = make_unique<Node<T>>();//构造一个Node指针
node->data = data;
node->next = move(head.next);//将所有权交给node,head.next失去所有权。
head.next = move(node);//
}
void print(){
Node<T> * node = head.next.get();//获取指针
while(node){
cout<<node->data;
node = node->next.get();
}
}
}