c/c++ 数组的智能指针 使用

数组的智能指针 使用

数组的智能指针的限制:

1,unique_ptr的数组智能指针,没有*和->操作,但支持下标操作[]

2,shared_ptr的数组智能指针,有*和->操作,但不支持下标操作[],只能通过get()去访问数组的元素。

3,shared_ptr的数组智能指针,必须要自定义deleter

小例子

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class test{
public:
  explicit test(int d = 0) : data(d){cout << "new" << data << endl;}
  ~test(){cout << "del" << data << endl;}
  void fun(){cout << data << endl;}
public:
  int data;
};
int main(){
  //test* t = new test[2];                                                      
  unique_ptr<test[]> up(new test[2]);
  up[0].data = 1;
  up[0].fun();
  up[1].fun();
  shared_ptr<test> sp(new test[2], [](test* p){delete [] p;});
  (sp.get())->data = 2;//数组的第一个元素                                       
  sp->data = 10;
  test& st = *sp;
  st.data = 20;
  (sp.get() + 1)->data = 3;//数组的第二个元素                                   
  return 0;
}

github完整代码

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

posted @ 2018-09-29 20:15  小石王  阅读(5347)  评论(0编辑  收藏  举报