數組與智能指針


數組的智能指針的限制

  • 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));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM