1 scoped_array智能指针特点
与scoped_ptr不同的是scoped_array智能指针管理new出来的数组空间,同样的是智能指针所管理的空间不能转移,但是可以通过成员方法reset让它去管理新的内存空间。
在使用时要注意以下几点
1、构造函数接受的指针p必须是new[]的结果,而不能是new表达式的结构
2、没有*、->操作符重载(但是可以扩展)
3、析构函数使用delete[]释放资源,而不是delete
4、提供operator[]操作符重载,可以向普通数组一样用下标访问元素
2 scoped_array智能指针实现
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vld.h>
using namespace std;
template <class T>
class scoped_array
{
public:
scoped_array(T* p = 0) :ptr(p) {}
// 注意析构时释放空间用的是delete[]
~scoped_array() { delete[] ptr; }
typedef scoped_array<T> this_type;
// 重设局部智能指针所管理的空间,与Reset1方法所不同的是
// 释放原来管理的空间不是通过直接调用delete
// 而是通过一个无名的临时对象,在交换ptr的值后
// 无名临时对象在析构时调用delete函数去释放交换后的ptr指向的空间
void Reset2(T *p = 0)
{
this_type(p).swap(*this);
}
void swap(scoped_array<T> &bref)
{
T* tmp = bref.ptr;
bref.ptr = ptr;
ptr = tmp;
}
// 重设局部智能指针所管理的空间,要注意原来空间的释放
// 注意delete释放空间用的是delete[]
void Reset1(T* p = 0)
{
if (ptr != p && ptr != 0)
delete[] ptr;
ptr = p;
}
// 功能扩展,boost库中的scoped_array不提供此方法
T& operator*()const
{
return ptr[0];
}
// 功能扩展,boost库中的scoped_array不提供此方法
T* operator+(int pos)
{
return ptr + pos;
}
// 重载[] ,使智能指针有数组[]访问的属性
T& operator[](int pos)
{
return ptr[pos];
}
private:
scoped_array(const scoped_array<T> &) {}
scoped_array<T>& operator=(const scoped_array<T> &) {}
T* ptr;
};
int main()
{
int *p = new int[10];
scoped_array<int> pa(p);
for (int i = 0; i < 10; i++)
{
pa[i] = i;
cout << pa[i] << " ";
}
cout << endl;
// 功能扩展,boost库中不提供*操作符的重载
*pa = 10;
cout << *pa << endl;
// 功能扩展,boost库中不提供+操作符的重载
*(pa + 5) = 100;
cout << pa[5] << endl;
// 重设所管理的空间
int *p2 = new int[20];
pa.Reset1(p2);
for (int i = 0; i < 20; i++)
{
pa[i] = 10 + i;
cout << pa[i] << " ";
}
cout << endl;
system("pause");
return 0;
}