#include<iostream>
using namespace std;
#include<string>
class myString {
public:
myString() {
cout << "默认构造函数" << endl;
_str = new char[5]; //以头部的4个字节来描述引用次数
_str[4] = 0;
getCount() = 1;
}
myString(const char* str) {
cout << "带参构造函数" << endl;
_str = new char[strlen(str) + 1 + 4];
strncpy_s(_str + 4, strlen(str) + 1, str, strlen(str));
getCount() = 1;
}
myString(const myString &src) {
cout << "拷贝构造函数" << endl;
_str = src._str;
getCount()++; //仅仅是引用次数加1
}
myString& operator = (const myString &src) {
cout << "赋值运算符重载" << endl;
if (this == &src) { //防止自赋值
return *this;
}
if (0 == --getCount()) { //进行等号赋值时,自身引用计数执行完成是需要减去1的
delete[]_str;
}
_str = src._str;
getCount()++;
return *this;
}
~myString() {
cout << "析构函数" << endl;
if (0 == --getCount()) {
delete[]_str;
}
}
char& operator[](int pos) { //该函数有改值的嫌疑
cout << "取值函数" << endl;
if (getCount() > 1) { //至少被引用两次
getCount()--;
char *tmp = _str + 4;
_str = new char[strlen(tmp) + 1 + 4];
strncpy_s(_str + 4, strlen(tmp) + 1, tmp, strlen(tmp));
getCount() = 1;
}
return _str[pos + 4];
}
private:
int &getCount() { return *(int *)_str; } //精华:引用计数
char *_str;
friend ostream& operator<<(ostream& out, const myString&str);
};
ostream& operator<<(ostream& out, const myString&str) {
out << str._str + 4 << endl;
return out;
}
int main()
{
myString s1;
myString s2("hello");
s1 = s2;
cout << s1;
myString s3(s2);
cout << "s2 ";
cout << s2 << endl;
cout << "s3 ";
cout << s3 << endl;
s3[0] = 'a';
cout << "s3 ";
cout << s3 << endl;
system("pause");
return 0;
}
图1 VS2017下运行结果