首页 > 编程语言 > 详细

数组与智能指针

时间:2020-04-15 13:06:30      阅读:60      评论:0      收藏:0      [点我收藏+]

数组的智能指针的限制

  • unique_ptr 的数组智能指针,没有*-> 操作,但支持下标操作[]。
  • shared_ptr 的数组智能指针,有 *-> 操作,但不支持下标操作[],只能通过 get() 去访问数组的元素。
  • 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;
};

unique_ptr 与数组:

int main()
{
	unique_ptr<test[]> up(new test[2]);
	up[0].data = 1;
	up[1].data = 2;
	up[0].fun();
	up[1].fun();

	return 0;
}

shared_ptr 与数组:

int main()
{
	shared_ptr<test[]> sp(new test[2], [](test *p) { delete[] p; });
	(sp.get())->data = 2;
	(sp.get()+1)->data = 3;

	(sp.get())->fun();
	(sp.get()+1)->fun();

	return 0;
}

五种智能指针指向数组的方法

  • shared_ptr 与 deleter (函数对象)
template<typename T>
struct array_deleter {
	void operator()(T const* p)
	{
		delete[] p;
	}
};

std::shared_ptr<int> sp(new int[10], array_deleter<int>());
  • shared_ptr 与 deleter (lambda 表达式)
std::shared_ptr<int> sp(new int[10], [](int* p) {delete[]p; });
  • shared_ptr 与 deleter ( std::default_delete)
std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());
  • 使用 unique_ptr
std::unique_ptr<int[]> up(new int[10]); //@ unique_ptr 会自动调用 delete[]
  • 使用 vector<int>
typedef std::vector<int> iarray;
std::shared_ptr<iarray> sp(new iarray(10));

数组与智能指针

原文:https://www.cnblogs.com/xiaojianliu/p/12704192.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!