#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
struct Aux {
char* buff{ nullptr };
int length{ 0 };
int count{ 0 };
Aux() : buff(nullptr), length(0), count(0)
{
cout << " MyStr default AUX constr.\n";
}
Aux(const char* buff1) : count(0), length(0)
{
length = strlen(buff1);
count++;
buff = new char[length + 1];
strcpy(buff, buff1);
cout << " MyStr AUX constr.\n";
}
~Aux() {
delete[] buff;
cout << " Aux destructor\n";
}
};
class MyStr {
Aux* pAux{ nullptr };
public:
MyStr() : pAux(nullptr)
{
cout << " MyStr default STR constr.\n";
}
MyStr(const char* init_val)
{
if (init_val != nullptr && *init_val != '\0')
{
pAux = new Aux();
pAux->length = strlen(init_val);
pAux->buff = new char[pAux->length + 1];
pAux->count = 1;
strcpy(pAux->buff, init_val);
}
cout << "MyStr( char * ) constr: " << pAux->buff << endl;
}
MyStr(Aux* pAuxOther) : pAux(pAuxOther)
{
if (pAuxOther != nullptr) {
pAuxOther->count++;
cout << " MyStr copy const.\n";
}
}
MyStr(const MyStr& other) : pAux(other.pAux) {
pAux->count++;
}
MyStr operator+(const MyStr& other) const {
int newLen = pAux->length + other.pAux->length;
char* newBuff = new char[newLen + 1];
strcpy(newBuff, pAux->buff);
strcat(newBuff, other.pAux->buff);
Aux* newAux = new Aux();
newAux->buff = newBuff;
newAux->length = newLen;
newAux->count = 1;
pAux->count++;
other.pAux->count++;
return MyStr(newAux);
}
MyStr operator=(const MyStr& other) {
if (pAux) {
pAux->count--;
if (pAux->count == 0) {
delete pAux;
}
}
pAux = other.pAux;
pAux->count++;
}
~MyStr()
{
cout << " MyStr destr.\n";
if (pAux) {
pAux->count--;
if (pAux->count == 0) {
delete pAux;
}
}
}
};
int main() {
Aux aux("Hello");
Aux* pAux = &aux;
MyStr a(pAux);
MyStr s1("Hello");
MyStr s2(" World");
MyStr s3 = s1 + s2;
return 0;
}