數組的智能指針的限制
- 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));