整理代码
1、unique_ptr 指针
#include <iostream>
#include <memory>
using namespace std;
class Demo
{
public:
Demo(){cout<<"无参构造"<<endl;}
~Demo(){cout<<"Demo的析构函数"<<endl;}
};
int main()
{
//unique_ptr指针
//1、使用堆空间进行初始化
unique_ptr<Demo> p1(new Demo);
cout<<p1.get()<<endl;
//2、使用原始指针进行初始化
Demo *p = new Demo;
cout << p<<endl;
unique_ptr<Demo> p2(p);
cout <<"p2="<<p2.get()<<endl;
//swap交换
swap(p1,p2);
cout <<"交换后:"<<"p1="<<p1.get()<<"\n"<<"p2="<<p2.get()<<endl;
//3、使用函数初始化
unique_ptr<Demo> p3=make_unique<Demo>();
p3=nullptr;
cout<<"p3="<<p3.get()<<endl;
unique_ptr<Demo> p4;
//4、想要P4独占P2指向的空间 move函数(智能指针)
p4=move(p2);
cout<<"p2="<<p2.get()<<endl;
cout<<"p4="<<p4.get()<<endl;
//释放p4对空间的所有权 返回首地址
Demo *test=p4.release();
cout <<"p4="<<p4.get()<<endl;
cout <<"test="<<test<<endl;
p4.reset(); //调用析构函数 释放空间所有权,释放堆区空间
cout << "p4="<<p4.get()<<endl;
return 0;
}
2、共享指针和弱智能指针共用
#include <iostream>
#include <memory>
//使用weak和share解决循环引用
using namespace std;
class Test;
class Demo
{
public:
weak_ptr<Test> t;
Demo(){cout <<"无参构造"<<endl;}
~Demo(){cout << "Demo的析构" << endl;}
};
class Test
{
public:
weak_ptr<Demo> d;
Test(){cout << "Test的无参构造" << endl;}
~Test(){cout << "Test的析构" << endl;}
};
int main()
{
shared_ptr<Demo> p1(new Demo);
shared_ptr<Test> p2(new Test);
p1->t=p2;
p2->d=p1;
cout <<"p1的计数="<<p1.use_count()<<endl;
cout <<"p2的计数="<<p2.use_count()<<endl;
weak_ptr<Demo> p3(p1);
cout <<"p1计数="<<p1.use_count()<<endl;
return 0;
}
2、思维导图