【c++】模拟实现boost库下的scoped_array

本文介绍了一个简单的scoped_array类模板的实现,该类模仿了Boost库中的scoped_array特性,用于自动管理动态分配的数组资源,提供了reset、swap等成员函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//模拟实现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;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值