1. 程式人生 > >c/c++ 數組的智能指針 使用

c/c++ 數組的智能指針 使用

xpl temp vector 技術分享 amp uniq get() href cpp

數組的智能指針 使用

數組的智能指針的限制:

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

c/c++ 數組的智能指針 使用