用智能指针管理容器及内存紧凑

   做了一个小练习,包括用智能指针去管理容器,容器的内存紧凑化问题,以及智能指针资源的复制与释放,希望对大家有参考价值。

#include <string>
#include <iostream> 
#include <vector>
#include <memory>
using namespace std;

class Point
{
public:
    Point(int a):m_a(a)
    {	}
    Point(const Point& p)
   {	m_a=p.m_a;	}
    ~Point()
    { cout<<"Point descontruction.."<<endl; }
	int m_a;
};

int main()
{
	auto_ptr< vector<Point> > PtrvMy(new vector<Point>);/////首先声明一个智能指针,用它去管理vector
	PtrvMy->reserve(1);//////预先分配很小的内存,以便观察内存的增长
	for(int i=0;i<10;i++)
	{	
		Point a(i);
		PtrvMy->push_back(a);//////这里内存不够时,会近似double地增长
		cout<<i<<","<<PtrvMy->capacity()<<endl;
	}
	vector<Point>(*PtrvMy).swap(*PtrvMy); //////把智能指针管理的vector进行内存紧凑化,去掉没有使用的内存
	cout<<"swap self....."<<PtrvMy->capacity()<<endl;

	vector<Point> vHis;
	vHis.reserve(10000);/////注意预先分配了很大的内存
	vHis=*PtrvMy;/////把智能指针的资源复制一份给一个普通变量,注意不是复制智能指针本身,不存在控制权转移问题
	cout<<"assignment to other....."<<vHis.capacity()<<endl;/////普通的赋值不会紧凑化左值容器
	vHis.swap(*PtrvMy);///////通过swap赋值能去掉左值容器多余的内存
	cout<<"swap with other....."<<vHis.capacity()<<endl;
	
	cout<<"free the auto ptr....."<<endl;
	PtrvMy.~auto_ptr();//////主动销毁智能指针管理的资源
	cout<<"free the vector"<<endl;
	/////但是这里会出现问题,因为编译器会主动再去销毁这个智能指针(他是局部变量),所以资源被释放了两次
 }

运行结果为:

猜你喜欢

转载自blog.csdn.net/wjj547670933/article/details/47252471