讲智能指针的文件已经很多了,大体意思都是为了避免C++中对象被new却未delete而引起的内存泄露问题。使用VC2005进行个简单的例子:
建立一个console application, 建个CStudent类:
#include <atlstr.h>
class CStudent
{
public:
CStudent();
~CStudent();
CString getName();
int getAge();
void setName(CString name);
void setAge(int age);
private:
CString mName;
int mAge;
};
然后是正文:
#include "CStudent.h"
#include <memory>
using namespace std;
void f()
{
std::auto_ptr<CStudent> pt(new CStudent());
pt->setAge(30);
cout<<"age is: "<<pt->getAge();
}
int _tmain(int argc, _TCHAR* argv[])
{
f();
system("PAUSE");
return 0;
}
运行结果是:
age is: 30
建立一个console application, 建个CStudent类:
#include <atlstr.h>
class CStudent
{
public:
CStudent();
~CStudent();
CString getName();
int getAge();
void setName(CString name);
void setAge(int age);
private:
CString mName;
int mAge;
};
然后是正文:
#include "CStudent.h"
#include <memory>
using namespace std;
void f()
{
std::auto_ptr<CStudent> pt(new CStudent());
pt->setAge(30);
cout<<"age is: "<<pt->getAge();
}
int _tmain(int argc, _TCHAR* argv[])
{
f();
system("PAUSE");
return 0;
}
运行结果是:
age is: 30
本文通过一个简单的C++示例介绍了如何使用智能指针来防止内存泄漏问题。示例中创建了一个CStudent类,并利用std::auto_ptr自动管理对象的生命周期。
355

被折叠的 条评论
为什么被折叠?



