MCPcopy Create free account
hub / github.com/EricPengShuai/Interview / MemoryBlock

Class MemoryBlock

STL/move.cpp:7–118  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5using namespace std;
6
7class MemoryBlock
8{
9public:
10
11 // Simple constructor that initializes the resource.
12 explicit MemoryBlock(size_t length)
13 : _length(length)
14 , _data(new int[length])
15 {
16 std::cout << "In MemoryBlock(size_t). length = "
17 << _length << "." << std::endl;
18 }
19
20 // Destructor.
21 ~MemoryBlock()
22 {
23 std::cout << "In ~MemoryBlock(). length = "
24 << _length << ".";
25
26 if (_data != nullptr)
27 {
28 std::cout << " Deleting resource.";
29 // Delete the resource.
30 delete[] _data;
31 }
32
33 std::cout << std::endl;
34 }
35
36 // Copy constructor.
37 MemoryBlock(const MemoryBlock& other)
38 : _length(other._length)
39 , _data(new int[other._length])
40 {
41 std::cout << "In MemoryBlock(const MemoryBlock&). length = "
42 << other._length << ". Copying resource." << std::endl;
43
44 std::copy(other._data, other._data + _length, _data);
45 }
46
47 // Copy assignment operator.
48 MemoryBlock& operator=(const MemoryBlock& other)
49 {
50 std::cout << "In operator=(const MemoryBlock&). length = "
51 << other._length << ". Copying resource." << std::endl;
52
53 if (this != &other)
54 {
55 // Free the existing resource.
56 delete[] _data;
57
58 _length = other._length;
59 _data = new int[_length];
60 std::copy(other._data, other._data + _length, _data);
61 }
62 return *this;
63 }
64

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected