讲智能指针的文件已经很多了,大体意思都是为了避免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