当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c/c++ 数组的智能指针 使用

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

2018年09月30日  | 移动技术网IT编程  | 我要评论

塞尔维亚国家队,盈钻网贷,胡伊萱的qq空间

数组的智能指针 使用

数组的智能指针的限制:

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;
}

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

本人微信:xiaoshitou5854

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网