| 3 | #include <cstring> |
| 4 | |
| 5 | class MyString |
| 6 | { |
| 7 | private: |
| 8 | int buf_len; |
| 9 | int * refcount; |
| 10 | char * characters; |
| 11 | public: |
| 12 | MyString(int buf_len = 64, const char * data = NULL) |
| 13 | { |
| 14 | std::cout << "Constructor(int, char*)" << std::endl; |
| 15 | this->buf_len = buf_len; |
| 16 | this->refcount = new int[1]{1}; // initialized to 1 |
| 17 | this->characters = new char[buf_len]{}; |
| 18 | if(data) |
| 19 | memcpy(this->characters, data, buf_len); |
| 20 | } |
| 21 | MyString(const MyString & ms) |
| 22 | { |
| 23 | std::cout << "Constructor(MyString&)" << std::endl; |
| 24 | this->buf_len = ms.buf_len; |
| 25 | this->refcount = ms.refcount; |
| 26 | this->characters = ms.characters; |
| 27 | this->refcount[0]++; |
| 28 | } |
| 29 | void release() |
| 30 | { |
| 31 | this->refcount[0]--; |
| 32 | if(this->refcount[0] == 0) |
| 33 | { |
| 34 | this->buf_len = 0; |
| 35 | delete this->refcount; |
| 36 | delete this->characters; |
| 37 | } |
| 38 | else |
| 39 | { |
| 40 | this->buf_len = 0; |
| 41 | this->refcount = NULL; |
| 42 | this->characters = NULL; |
| 43 | } |
| 44 | } |
| 45 | ~MyString() |
| 46 | { |
| 47 | release(); |
| 48 | } |
| 49 | MyString & operator=(const MyString &ms) |
| 50 | { |
| 51 | release(); |
| 52 | this->buf_len = ms.buf_len; |
| 53 | this->refcount = ms.refcount; |
| 54 | this->characters = ms.characters; |
| 55 | this->refcount[0]++; |
| 56 | return *this; |
| 57 | } |
| 58 | friend std::ostream & operator<<(std::ostream & os, const MyString & ms) |
| 59 | { |
| 60 | os << "buf_len = " << ms.buf_len; |
| 61 | os << ", refcount = " << ms.refcount[0]; |
| 62 | os << ", characters = " << static_cast<void*>(ms.characters); |
nothing calls this directly
no outgoing calls
no test coverage detected