目录
概念:
auto_ptr智能指针已在C++17中移除。可用作学习智能指针的入门。
auto_ptr又称资源转移指针,即发生拷贝构造或=号赋值后,原auto_ptr指针为空。
使用标准库auto_ptr指针:
头文件:#include <memory>
自定义一个Stu类:
#include <iostream>
#include <memory>
using namespace std;
class Stu
{
private:
string name;
int age;
public:
Stu(string name, int age)
{
this->name = name;
this->age = age;
cout << "Stu的构造" << endl;
}
~Stu()
{
cout << "Stu的析构" << endl;
}
void showInfo()
{
cout << "姓名:" << this->name << " 年龄:" << this ->age << endl;
}
};
标准库auto_ptr指针:
int main()
{
//使用系统auto_ptr智能指针
auto_ptr<Stu> ptr1(new Stu("zhangsan", 20));
auto_ptr<Stu> ptr2 = ptr1;
cout << "-------------- " << endl;
//原因是,auto_ptr发生权限转移,会将自身的资源释放,ptr1就无内容了
ptr2->showInfo(); //姓名:zhangsan 年龄:20
// ptr1->showInfo(); //姓名: (为空,且不往下执行了)
}
运行结果:
自定义智能指针的底层实现:
仍用上边的Stu类。
自定义智能指针类:
//自己实现atuo_ptr类
template <class T>
class AUTO_ptr
{
private:
T * ptr;
public:
//构造函数,将初始化传的指针赋值给本类指针,如果空传参,则给指针默认赋空指针
AUTO_ptr(T* ptr = nullptr)
{
this->ptr = ptr;
}
~AUTO_ptr()
{
delete ptr;
}
//拷贝构造
AUTO_ptr(const AUTO_ptr& other)
{
this->ptr = other.ptr;
const_cast<AUTO_ptr&> (other).ptr = nullptr;
}
//=号重载
AUTO_ptr& operator = (const AUTO_ptr& other)
{
if(this == &other)
{
return *this;
}
if(this->ptr != nullptr)
{
delete ptr;
this->ptr = other.ptr;
const_cast<AUTO_ptr&> (other).ptr = nullptr;
}
return *this;
}
T& operator* ()
{
return *ptr;
}
T* operator-> ()
{
return ptr;
}
T* get()
{
return ptr;
}
};
主函数:
int main()
{
//用自己定义的auto_ptr类
AUTO_ptr<Stu> ptr3(new Stu("lisi", 22));
AUTO_ptr<Stu> ptr4 = ptr3;
cout << "-----------------" << endl;
ptr4->showInfo(); //姓名:lisi 年龄:22
// ptr3->showInfo(); //姓名: (为空,且不往下执行了)
cout << "----------" << endl;
ptr4.get()->showInfo(); //姓名:lisi 年龄:2
(*ptr4).showInfo(); //姓名:lisi 年龄:22
}
运行结果: