MCPcopy Create free account
hub / github.com/Extra-Creativity/Modern-Cpp-Basics / MyIntVector

Class MyIntVector

09-Move Semantics Basics/code/MyIntVector.h:6–69  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <utility>
5
6class MyIntVector
7{
8 int *ptr_ = nullptr;
9 std::size_t size_ = 0;
10
11 void Clear_() noexcept { delete[] ptr_; }
12
13 void Reset_() noexcept { ptr_ = nullptr, size_ = 0; }
14
15 // This method assumes currently ptr_ = nullptr && size_ = 0.
16 void AllocAndCopy_(const MyIntVector &another)
17 {
18 if (another.size_ == 0)
19 return;
20 std::unique_ptr<int[]> arr{ new int[another.size_] };
21 std::memcpy(arr.get(), another.ptr_, another.size_ * sizeof(int));
22
23 ptr_ = arr.release();
24 size_ = another.size_;
25 return;
26 }
27
28public:
29 MyIntVector(std::size_t initSize)
30 {
31 if (initSize == 0)
32 return;
33 ptr_ = new int[initSize], size_ = initSize;
34 }
35 int &operator[](std::size_t idx) { return ptr_[idx]; }
36 int operator[](std::size_t idx) const { return ptr_[idx]; }
37 auto size() const { return size_; }
38
39 MyIntVector(const MyIntVector &another) { AllocAndCopy_(another); }
40
41 MyIntVector(MyIntVector &&another) noexcept
42 : ptr_{ std::exchange(another.ptr_, nullptr) },
43 size_{ std::exchange(another.size_, 0) }
44 {
45 }
46
47 MyIntVector &operator=(const MyIntVector &another)
48 {
49 if (this == &another)
50 return *this;
51
52 Clear_();
53 Reset_(); // For basic exception guarantee.
54 AllocAndCopy_(another);
55 return *this;
56 }
57
58 MyIntVector &operator=(MyIntVector &&another) noexcept
59 {
60 if (this == &another)
61 return *this;
62
63 Clear_();

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected