//模拟实现boost库下的scoped_array #include <iostream> #include <assert.h> using namespace std; template <class T> class scoped_array { private: T * px; scoped_array(scoped_array const &); scoped_array& operator=(scoped_array const &); void operator==(scoped_array const &)const; void operator!=(scoped_array const &)const; public: scoped_array(T * p = 0) :px(p) {} ~scoped_array() { delete[] px; } void reset(T * p = 0) { assert(p == 0 || p != px); scoped_array<T>(p).swap(*this); } T& operator[](int i)const { assert(px != 0); assert(i >= 0); return px[i]; } T* get()const { return px; } void swap(scoped_array & b) { T *tmp = px; px = b.px; b.px = tmp; } }; int main() { int *arr = new int[100]; arr[0] = 50; scoped_array<int> ptr(arr); cout << ptr[0] << endl; return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-10 06:32:14