Shared_ptr使用详解
在之前参加项目时,有一条准则为不使用原生态指针,而使用智能指针。那么我将在本文中介绍shard_ptr的内容。本文分两个部分组成,第一部分是讲解shard_ptr的使用方法,(至于智能指针的理解,此处不赘述)以及第二部分使用shared_ptr实现链表的部分功能,(其他功能也是类似的而已)。
(知识点摘自cplusplus)
构造部分
构造函数有4个参数分别有以下含义:
#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-