#include <iostream>
#include <cstring>
class MyString
{
public:
MyString() : data(nullptr) {}
~MyString()
{
delete[] data;
}
MyString(const MyString& other) //copy constructor
{
data = new char[strlen(other.c_str()) + 1]; // another allocation
strcpy(data, other.c_str()); // copy over the old string buffer
}
MyString(MyString&& other)
{
data = other.data;
other.data = nullptr;
}
void set(const char* str)
{
char* newString = new char[strlen(str) + 1];
strcpy(newString, str);
delete[] data;
data = newString;
}
const char* c_str() const
{
return data;
}
private:
char* data;
};
int main()
{
MyString str;
str.set("test");
std::cout << str.c_str() << "\n";
MyString anotherStr(str); // copy over contents.
std::cout << anotherStr.c_str() << "\n";
MyString AndAnotherOne(std::move(str)); // now _move_ str into AndAnotherOne
std::cout << AndAnotherOne.c_str() << "\n"; // we shouldn't use `str` now anymore as it's data has been "stolen"
std::cin.get();
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3N0cmluZz4KCmNsYXNzIE15U3RyaW5nCnsKcHVibGljOgogICAgTXlTdHJpbmcoKSA6IGRhdGEobnVsbHB0cikge30KCiAgICB+TXlTdHJpbmcoKQogICAgewogICAgICAgIGRlbGV0ZVtdIGRhdGE7CiAgICB9CgogICAgTXlTdHJpbmcoY29uc3QgTXlTdHJpbmcmIG90aGVyKSAvL2NvcHkgY29uc3RydWN0b3IKICAgIHsgCiAgICAgICAgZGF0YSA9IG5ldyBjaGFyW3N0cmxlbihvdGhlci5jX3N0cigpKSArIDFdOyAvLyBhbm90aGVyIGFsbG9jYXRpb24KICAgICAgICBzdHJjcHkoZGF0YSwgb3RoZXIuY19zdHIoKSk7IC8vIGNvcHkgb3ZlciB0aGUgb2xkIHN0cmluZyBidWZmZXIKICAgIH0KCiAgICBNeVN0cmluZyhNeVN0cmluZyYmIG90aGVyKQogICAgewogICAgICAgIGRhdGEgPSBvdGhlci5kYXRhOwogICAgICAgIG90aGVyLmRhdGEgPSBudWxscHRyOwogICAgfQoKICAgIHZvaWQgc2V0KGNvbnN0IGNoYXIqIHN0cik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