fork download
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. class MyString
  5. {
  6. public:
  7. MyString() : data(nullptr) {}
  8.  
  9. ~MyString()
  10. {
  11. delete[] data;
  12. }
  13.  
  14. MyString(const MyString& other) //copy constructor
  15. {
  16. data = new char[strlen(other.c_str()) + 1]; // another allocation
  17. strcpy(data, other.c_str()); // copy over the old string buffer
  18. }
  19.  
  20. MyString(MyString&& other)
  21. {
  22. data = other.data;
  23. other.data = nullptr;
  24. }
  25.  
  26. void set(const char* str)
  27. {
  28. char* newString = new char[strlen(str) + 1];
  29. strcpy(newString, str);
  30. delete[] data;
  31. data = newString;
  32. }
  33.  
  34. const char* c_str() const
  35. {
  36. return data;
  37. }
  38. private:
  39. char* data;
  40. };
  41.  
  42.  
  43. int main()
  44. {
  45. MyString str;
  46. str.set("test");
  47. std::cout << str.c_str() << "\n";
  48. MyString anotherStr(str); // copy over contents.
  49. std::cout << anotherStr.c_str() << "\n";
  50. MyString AndAnotherOne(std::move(str)); // now _move_ str into AndAnotherOne
  51. std::cout << AndAnotherOne.c_str() << "\n"; // we shouldn't use `str` now anymore as it's data has been "stolen"
  52. std::cin.get();
  53. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
test
test
test