Matrices y punteros inteligentes

Restricciones en punteros inteligentes de matriz

  • unique_ptr Smart Array puntero, sin *y ->operación, pero apoya el operador subíndice [].
  • shared_ptr matriz de punteros inteligentes, existe *y ->funciona, pero no admite el operador subíndice [], sólo puede ser get()el acceso a los elementos de la matriz.
  • El puntero inteligente de matriz shared_ptr debe personalizarse.
#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 y 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 y 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;
}

Cinco punteros inteligentes a los métodos de matriz

  • shared_ptr y deleter (objeto de función)
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 y deleter (expresión 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[]>());
  • Use unique_ptr
std::unique_ptr<int[]> up(new int[10]); //@ unique_ptr 会自动调用 delete[]
  • Para utilizar vector<int>
typedef std::vector<int> iarray;
std::shared_ptr<iarray> sp(new iarray(10));

Supongo que te gusta

Origin www.cnblogs.com/xiaojianliu/p/12704192.html
Recomendado
Clasificación