您的位置:首页 > 其它

使用auto_ptr来自动释放内存

2006-07-04 18:01 549 查看
标准的STL模板库中,有一个auto_ptr模板类,它能够自动释放用new分配的内存。对于在局部变量中内存的分配和释放,能够得到有效的处理,避免了内存泄漏。请看下面的演示代码:
#include <iostream>
#include <memory>

using namespace std;

class Base
{
int id;

public:
Base( int _id = 0 )
: id( _id )
{
cout << "Base constructor" << endl;
}
virtual ~Base()
{
cout << "Base destructor" << endl;
}

inline int getId() const
{
return id;
}

inline void setId( int _id )
{
id = _id;
}
};

static void seeit( int id )
{
cout << "id = " << id << endl;
auto_ptr<Base> res( new Base );

if ( id < 0 )
return;
res->setId( id );
cout << res->getId() << endl;
}

int main( void )
{

for ( int i = 2; i >= -2; -- i )
{
seeit( i );
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: