shared_ptr

  1. //
  2. // Created by Administrator on 2022/2/21.
  3. //
  4. /*
  5. * 智能指针 shared_ptr
  6. */
  7. #include<bits/stdc++.h>
  8. using namespace std;
  9. int main() {
  10. shared_ptr<int> p1(new int(10));
  11. shared_ptr<int> p2(p1);
  12. cout<<*p2<<endl;
  13. p1.reset(); // 引用计数 -1
  14. if(p1) {
  15. cout<<"p1 不为空"<<endl;
  16. }
  17. else{
  18. cout<<"p1 为空"<<endl;
  19. }
  20. cout<<*p2<<endl;
  21. cout<<p2.use_count()<<endl;
  22. return 0;
  23. }

unique_ptr

  1. //
  2. // Created by Administrator on 2022/2/21.
  3. //
  4. /*
  5. * unique_ptr 不共享内存,没有拷贝构造函数,只有移动构造函数
  6. */
  7. #include<bits/stdc++.h>
  8. using namespace std;
  9. int main() {
  10. unique_ptr<int> p5(new int);
  11. *p5 = 10;
  12. int *p = p5.release(); // 释放所有权,但是堆内存不会销毁
  13. cout<<*p<<endl;
  14. if(p5) {
  15. cout<<"p5 is not nullptr"<<endl;
  16. }
  17. else {
  18. cout<<"p5 is nullptr"<<endl;
  19. }
  20. unique_ptr<int> p6;
  21. p6.reset(p); // 释放当前指向的内存并且获取 p 指向的堆内存所有权
  22. cout<<*p6<<endl;
  23. return 0;
  24. }

weak_ptr

  1. //
  2. // Created by Administrator on 2022/2/21.
  3. //
  4. /*
  5. * weak_ptr
  6. */
  7. #include<bits/stdc++.h>
  8. using namespace std;
  9. int main() {
  10. shared_ptr<int> sp1(new int(10));
  11. shared_ptr<int> sp2(sp1);
  12. weak_ptr<int> wp(sp2);
  13. cout<<wp.use_count()<<endl;
  14. sp2.reset();
  15. cout<<wp.use_count()<<endl;
  16. cout<<*(wp.lock())<<endl;
  17. return 0;
  18. }