0%

自己实现unique_ptr

2020年3月16日 下午4:55

了解一下std::move

  • std::move - cppreference.com
  • std::move 用于_指示_对象 t 可以“被移动”,即允许从 t 到另一对象的有效率的资源传递。

test01_unique_ptr.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <utility>  // std::swap/move
#include "shape.h" // shape/shape_type/create_shape

template <typename T>
class smart_ptr {
public:
explicit smart_ptr(T* ptr = nullptr)
: ptr_(ptr) {}
~smart_ptr()
{
delete ptr_;
}
smart_ptr(smart_ptr&& other)
{
ptr_ = other.release();
}
smart_ptr& operator=(smart_ptr rhs)
{
rhs.swap(*this);
return *this;
}

T* get() const { return ptr_; }
T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_; }
operator bool() const { return ptr_; }
T* release()
{
T* ptr = ptr_;
ptr_ = nullptr;
return ptr;
}
void swap(smart_ptr& rhs)
{
using std::swap;
swap(ptr_, rhs.ptr_);
}

private:
T* ptr_;
};

int main()
{
smart_ptr<shape> ptr1{create_shape(shape_type::circle)};
//smart_ptr<shape> ptr2{ptr1}; // Cannot compile
smart_ptr<shape> ptr3;
//ptr3 = ptr1; // Cannot compile
ptr3 = std::move(ptr1); // OK
smart_ptr<shape> ptr4{std::move(ptr3)}; // OK
}