smart pointer--->When you call new,you don't have to call delete
unique pointer:
1.cannot be copied.They have to be unique!
比如:两个unique pointer指向同一内存,when one unique pointer die-->it will free that memery!
这样第二个指针就会指向已经被释放了的memory
查看memery.h
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
可以看到拷贝
unique_ptr构造函数构造函数是被禁止的!
所以不能这样初始化:
int main(int argc, char const *argv[])
{
{
std::unique_ptr<Entity> entity = new Entity();//error!
}
std::cin.get();
return 0;
}
正确初始化:
#include<iostream>
#include<string>
#define LOG(x) std::cout<<x<<std::endl;
class Entity
{
public:
Entity();
~Entity();
private:
};
Entity::Entity()
{
LOG("Created Entity!")
}
Entity::~Entity()
{
LOG("Destroyed Entity!")
}
int main(int argc, char const *argv[])
{
{
std::unique_ptr<Entity> entity(new Entity());
}
std::cin.get();
return 0;
}
以下两种初始化方式都可以,make_unique会更安全(防止new异常)
std::unique_ptr<Entity> entity(new Entity());
std::unique_ptr<Entity> entity = std::make_unique<Entity>();
设置断点看一下:
运行到std::unique_ptr<Entity> entity = std::make_unique<Entity>(); --->Created Entity!
出了{ }范围 --->Destroyed Entity!
2.unique_ptr point to a stack allocated object,when the stack allocated object dies,it will call delete ,and free that memery
以下转自:https://www.cnblogs.com/wangkeqin/p/9383658.html
一个unique_ptr"拥有“他所指向的对象。与shared_ptr不同,某个时刻只能有一个unique_ptr指向一个给定的对象。当unique_ptr被销毁时,它所指向的对象也被销毁。uniptr_ptr表达的是一种独占的思想。
Share Pointer
1.share pointer allocate another memery call control block--->store reference count
reference count --->keep track of how many references you have,when reference count =0 --> memery get deleted
设置断点看一下:
出了里头的范围{ }-->sharedEntity reference销毁了,但e0 reference 还在
直到出了外头的范围{ } e0 reference销毁后,reference cnt =0 --->自动调用析构函数释放内存!