1.智能指针是指针吗?智能指针不是指针,是一个类对象,只不过这个对象托管了另一个对象的自动析构,实现堆区的自动析构,这就是智能指针的特性
#include <iostream>
#include<memory>//智能指针的头文件
using namespace std;
//1.定义一个学生类
class Stu
{
private:
string name;
int age;
public:
Stu(string name,int age)
{
this->name=name;
this->age=age;
cout<<"这是Stu的构造函数"<<endl;
}
void showInfo()
{
cout<<"学生姓名:"<<this->name<<"年龄"<<this->age<<endl;
}
~Stu()
{
cout<<"Stu的析构函数"<<endl;
}
};
int main(int argc, char *argv[])
{
auto_ptr<Stu> stu_ptr(new Stu("zhangsan",18));
stu_ptr.get()->showInfo();
return 0;
}
封装一个智能指针类:
#include <iostream>
#include<memory>//智能指针的头文件
using namespace std;
//1.定义一个学生类
class Stu
{
private:
string name;
int age;
public:
Stu(string name,int age)
{
this->name=name;
this->age=age;
cout<<"这是Stu的构造函数"<<endl;
}
void showInfo()
{
cout<<"学生姓名:"<<this->name<<"年龄"<<this->age<<endl;
}
~Stu()
{
cout<<"Stu的析构函数"<<endl;
}
};
template<class T>
class Auto_ptr
{
private:
T* p; //定义一个指针指向堆区空间
public:
Auto_ptr(T* _p):p(_p) //初始化指针
{
cout<<"Auto_ptr的构造函数"<<endl;
}
~Auto_ptr()
{
delete p;
}
//get方法
T* get()
{
return p;
}
T* operator ->() //->号重载
{
return p;
}
Auto_ptr(const Auto_ptr&other)
{
this->p=other.p;
other.p=nullptr;
}
};
int main(int argc, char *argv[])
{
// auto_ptr<Stu> stu_ptr(new Stu("zhangsan",18));
// stu_ptr.get()->showInfo();
Auto_ptr<Stu> ptr(new Stu("zhangsan",18));
ptr->showInfo();
return 0;
}