[C++]Shared_ptr使用详解&&实现链表

Shared_ptr使用详解

在之前参加项目时,有一条准则为不使用原生态指针,而使用智能指针。那么我将在本文中介绍shard_ptr的内容。本文分两个部分组成,第一部分是讲解shard_ptr的使用方法,(至于智能指针的理解,此处不赘述)以及第二部分使用shared_ptr实现链表的部分功能,(其他功能也是类似的而已)。

(知识点摘自cplusplus)

构造部分

构造函数有4个参数分别有以下含义:

para

#include <algorithm>
#include <iostream>
#include <memory>
using namespace std;
/*
 default (1)
 constexpr shared_ptr() noexcept;
 from null pointer (2)
 constexpr shared_ptr(nullptr_t) : shared_ptr() {}
 from pointer (3)
 template <class U> explicit shared_ptr (U* p);
 with deleter (4)
 template <class U, class D> shared_ptr (U* p, D del);
 template <class D> shared_ptr (nullptr_t p, D del);
 with allocator (5)
 template <class U, class D, class Alloc> shared_ptr (U* p, D del, Alloc alloc);
 template <class D, class Alloc> shared_ptr (nullptr_t p, D del, Alloc alloc);
 copy (6)
 shared_ptr (const shared_ptr& x) noexcept;
 template <class U> shared_ptr (const shared_ptr<U>& x) noexcept;
 copy from weak (7)
 template <class U> explicit shared_ptr (const weak_ptr<U>& x);
 move (8)
 shared_ptr (shared_ptr&& x) noexcept;
 template <class U> shared_ptr (shared_ptr<U>&& x) noexcept;
 move from managed (9)
 template <class U> shared_ptr (auto_ptr<U>&& x);
 template <class U, class D> shared_ptr (unique_ptr<U,D>&& x);
 aliasing (10)
 template <class U> shared_ptr (const shared_ptr<U>& x, element_type* p)
 noexcept;
 */
struct C {
  int* data;
};

int main() {
  std::shared_ptr<int> p1;
  std::shared_ptr<int> p2(nullptr);
  std::shared_ptr<int> p3(new int);
  std::shared_ptr<int> p4(new int, std::default_delete<int>());
  std::shared_ptr<int> p5(new int, [](int* p) { delete p; },
                          std::allocator<int>());
  std::shared_ptr<int> p6(p5);
  std::shared_ptr<int> p7(std::move(p6));
  std::shared_ptr<int> p8(std::unique_ptr<int>(new int));
  std::shared_ptr<C> obj(new C);
  std::shared_ptr<int> p9(obj, obj-
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值