C++中的智能指针
智能指针的主要作用:防止未进行delete从而导致的内存泄露,使内存更加安全
智能指针的种类:
#include<memory>
使用new需要手工删除,而智能指针则不需要;
e1不再拥有e2,为空指针;e1 拥有权转移到e2;
example1:
#include<iostream>
#include<memory>
using namespace std;
class Entity{
public:
Entity() { puts("Entity created!"); }
~Entity() { puts("Entity destoryed!"); }
};
void ex1() {
puts("----------------");
puts("Entering ex1");
{
puts("Entering ex1::scope1");
auto e1=std::make_unique<Entity>();
puts("Leaving ex1::scope1");
}
puts("Leaving ex1");
};
int main() {
ex1();
return 0;
}
results:
----------------
Entering ex1
Entering ex1::scope1
Entity created!
Leaving ex1::scope1
Entity destoryed!
Leaving ex1
example2
void foo(std::unique_ptr<Entity>) {
puts("Entering foo");
puts("Leaving foo");
}
void ex2() {
puts("--------------");
puts("Entering ex2");
auto e1 = std::make_unique<Entity>();
foo(std::move(e1));
puts("Leaving ex2");
}
results:
--------------
Entering ex2
Entity created!
Entering foo
Leaving foo
Entity destoryed!
Leaving ex2
unique_ptr
的生命周期
在任何时刻,只能由一个对象或一个函数拥有它。
shared_ptr
的生命周期
主要用在多线程场景中,对于shared_ptr,在任何时刻,可以有多个对象和多个函数拥有它,当use_count变为0,最后一个拥有者被析构,生命周期结束。
总结:和new/delete说再见;用智能指针代替原始指针
尽可能多用std::unique_ptr相比于std::shared_ptr
参考视频:https://www.bilibili.com/video/BV1fK411H7CA