Hard Copy
出现原因:多个对象同时指向一块内存空间。
解决方案:所有的对象都拥有自己的内存数据。
11.2中的例子中,错误的罪魁祸首就是C++默认提供的Copy Constructor,它把指针直接赋值了。
- Provide a user-defined copy constructor. ```cpp MyString::MyString(const MyString & ms) { this->buf_len = 0; this->characters = NULL; create(ms.buf_len, ms.characters); }
- `create()` release the current memory and **allocate a new one.**- **会显示放当然内存,然后重新申请一个新的内存空间。**- `**t**his->characters` will not point to `ms.characters`.- 保证了当前对象的指针不跟参数的指针相同- **It's a hard copy!**第二个错误产生的原因:赋值运算符出现了问题<br />默认的运算符重载做了两个变量的复制,我们可以自定义运算符重载函数,- Provide a user-defined copy assignment- 使用create去申请内存,使得每个对象都有自己的内存,不在共享```cpp#pragma once#include <iostream>#include <cstring>class MyString{private:int buf_len;char *characters;public:MyString(int buf_len = 64, const char *data = NULL){std::cout << "Constructor(int, char*)" << std::endl;this->buf_len = 0;this->characters = NULL;create(buf_len, data);}MyString(const MyString &ms){std::cout << "Constructor(MyString&)" << std::endl;this->buf_len = 0;this->characters = NULL;create(ms.buf_len, ms.characters);}~MyString(){release();}MyString &operator=(const MyString &ms){create(ms.buf_len, ms.characters);return *this;}bool create(int buf_len, const char *data){release();this->buf_len = buf_len;if (this->buf_len != 0){this->characters = new char[this->buf_len]{};}if (data)strncpy(this->characters, data, this->buf_len);return true;}bool release(){this->buf_len = 0;if (this->characters != NULL){delete[] this->characters;this->characters = NULL;}return 0;}friend std::ostream &operator<<(std::ostream &os, const MyString &ms){os << "buf_len = " << ms.buf_len;os << ", characters = " << static_cast<void *>(ms.characters);os << " [" << ms.characters << "]";return os;}};
