*
和 ->
操作,但支持下标操作[]。*
和 ->
操作,但不支持下标操作[],只能通过 get()
去访问数组的元素。#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;
}
template<typename T>
struct array_deleter {
void operator()(T const* p)
{
delete[] p;
}
};
std::shared_ptr<int> sp(new int[10], array_deleter<int>());
std::shared_ptr<int> sp(new int[10], [](int* p) {delete[]p; });
std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());
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