智能指针
简单概括:在一个生存周期结束后,可自动释放内存,不需要在delete;
- auto_ptr
- unique_ptr
- shared_ptr
- weak_ptr
使用方法:
auto_ptr<类型>变量名(new类型)
使用:
auto_ptr
class test
{
public:
test() { cout << "构造test" << endl; }
~test() { cout << "析构test" << endl; };
};
void demo() {
test* t = new test();
}
int main(void) {
demo();
system("pause");
return 0;
}
根据上述代码,我们可以发现t为被释放,因此会造成严重问题,内存泄露,因此,我们此时考虑智能指针
有效的避免了内存泄漏的问题
智能指针的访问:
#include<iostream>
using namespace std;
class test
{
public:
test() { cout << "构造test" << endl; }
~test() { cout << "析构test" << endl; };
int a = 5;
};
int main(void) {
auto_ptr<test>v1(new test());
v1->a;
v1.get()->a;
//get()返回本身
(*v1).a;
system("pause");
return 0;
}
智能指针的重置:
auto_ptr<test>v1(new test());
v1.reset();//reset重置智能指针托管的内存地址,如果地址不一致,原来的会被析构掉
rest()内部:
void reset(_Ty* _Ptr = nullptr) noexcept {
if (_Ptr != _Myptr) {
delete _Myptr;
}
_Myptr = _Ptr;
}
Myptr为自身
但是,auto_ptr由于弊端,已经被unique_ptr所代替
弊端:
当我们使用=时
因此,我们现在使用unique_ptr:
Unique_ptr直接禁止了=
如果一定要p1指向的值指向p2的值,使用move把左值转成右值
此时p2为空
其他使用与auto_ptr相同
- shared_ptr
如果有一种方式,可以记录引用特定内存对象的智能指针数量,当复制或拷贝时,引用计数加1,当智能指针析构时,
引用计数减1,如果计数为0,代表已经没有指针指向这块内存,那么我们就释放它!这就是shared_ptr采用的策略!
记住:只有uses_count=0时才会释放内存
Weak_ptr:
weak_ptr设计的目的是为配合shared_ptr而引入的一种智能指针来协助shared_ptr工作,它可以从一个shared_ptr或另一个weak_ptr对象构造,
它的构造和析构不会引起引用计数的增加或减少.同时weak_ptr没有重载*和->但可以使用lock获得一个可以的shared_ptr对象