shared_ptr
//
// Created by Administrator on 2022/2/21.
//
/*
* 智能指针 shared_ptr
*/
#include<bits/stdc++.h>
using namespace std;
int main() {
shared_ptr<int> p1(new int(10));
shared_ptr<int> p2(p1);
cout<<*p2<<endl;
p1.reset(); // 引用计数 -1
if(p1) {
cout<<"p1 不为空"<<endl;
}
else{
cout<<"p1 为空"<<endl;
}
cout<<*p2<<endl;
cout<<p2.use_count()<<endl;
return 0;
}
unique_ptr
//
// Created by Administrator on 2022/2/21.
//
/*
* unique_ptr 不共享内存,没有拷贝构造函数,只有移动构造函数
*/
#include<bits/stdc++.h>
using namespace std;
int main() {
unique_ptr<int> p5(new int);
*p5 = 10;
int *p = p5.release(); // 释放所有权,但是堆内存不会销毁
cout<<*p<<endl;
if(p5) {
cout<<"p5 is not nullptr"<<endl;
}
else {
cout<<"p5 is nullptr"<<endl;
}
unique_ptr<int> p6;
p6.reset(p); // 释放当前指向的内存并且获取 p 指向的堆内存所有权
cout<<*p6<<endl;
return 0;
}
weak_ptr
//
// Created by Administrator on 2022/2/21.
//
/*
* weak_ptr
*/
#include<bits/stdc++.h>
using namespace std;
int main() {
shared_ptr<int> sp1(new int(10));
shared_ptr<int> sp2(sp1);
weak_ptr<int> wp(sp2);
cout<<wp.use_count()<<endl;
sp2.reset();
cout<<wp.use_count()<<endl;
cout<<*(wp.lock())<<endl;
return 0;
}