Arrays and smart pointers

Restrictions on array smart pointers

  • unique_ptr smart pointer array, without *and ->operation, but supports the subscript operator [].
  • shared_ptr smart pointer array, there *and ->operate, but does not support the subscript operator [], can only be get()access to elements of the array.
  • The shared_ptr array smart pointer must be customized.
#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 and array:

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 and array:

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

Five smart pointers to array methods

  • shared_ptr and deleter (function object)
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 and deleter (lambda expression)
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[]>());
  • Use unique_ptr
std::unique_ptr<int[]> up(new int[10]); //@ unique_ptr 会自动调用 delete[]
  • use vector<int>
typedef std::vector<int> iarray;
std::shared_ptr<iarray> sp(new iarray(10));

Guess you like

Origin www.cnblogs.com/xiaojianliu/p/12704192.html