fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstring>
  4.  
  5. using namespace std;
  6.  
  7. class Mystring {
  8. private:
  9. char* str;
  10. public:
  11. Mystring();
  12. Mystring(const char* s);
  13. Mystring(const Mystring& source);
  14. Mystring(Mystring&& source);
  15. ~Mystring();
  16.  
  17. Mystring& operator=(const Mystring& rhs);
  18. Mystring& operator=(Mystring&& rhs);
  19.  
  20. void display() const;
  21. int get_lenght() const;
  22. const char* get_str() const;
  23. };
  24.  
  25. int main() {
  26. vector <Mystring> stooges_vec;
  27. stooges_vec.push_back("Larry"); //11
  28. stooges_vec.push_back("Moe"); //12
  29. stooges_vec.push_back("Curly"); //13
  30.  
  31. return 0;
  32. }
  33.  
  34.  
  35.  
  36. //One-args constructor
  37. Mystring::Mystring(const char* s)
  38. : str{ nullptr } {
  39. if (s == nullptr) {
  40. str = new char[1];
  41. *str = '\0';
  42. }
  43. else {
  44. str = new char[std::strlen(s) + 1];
  45. std::strcpy(str, s);
  46. }
  47. }
  48.  
  49.  
  50.  
  51. //Copy constructor
  52. Mystring::Mystring(const Mystring& source)
  53. :str{ nullptr } {
  54. str = new char[std::strlen(source.str) + 1];
  55. std::strcpy(str, source.str);
  56. }
  57.  
  58.  
  59.  
  60. //Move constructor
  61. Mystring::Mystring(Mystring&& source)
  62. :str{ source.str } {
  63. source.str = nullptr;
  64. std::cout << "Move constructor called." << std::endl;
  65. }
  66.  
  67.  
  68.  
  69. //Destructor
  70. Mystring::~Mystring() {
  71. delete[] str;
  72. }
  73.  
  74.  
  75.  
  76. //Copy assignment
  77. Mystring& Mystring::operator=(const Mystring& rhs) {
  78. std::cout << "Copy assignment called." << std::endl;
  79. if (this == &rhs)
  80. return *this;
  81. delete[] str;
  82. str = new char[std::strlen(rhs.str) + 1];
  83. std::strcpy(str, rhs.str);
  84. return *this;
  85. }
  86.  
  87.  
  88.  
  89. //Move assignment
  90. Mystring& Mystring::operator=(Mystring&& rhs) {
  91. std::cout << "Move assignment called." << std::endl;
  92. if (this == &rhs)
  93. return *this;
  94. delete[] str;
  95. str = rhs.str;
  96. rhs.str = nullptr;
  97. return *this;
  98. }
Success #stdin #stdout 0s 4356KB
stdin
Standard input is empty
stdout
Move constructor called.
Move constructor called.
Move constructor called.