Basic MyString Move Semantics Implementation

  1. #ifndef MYSTRING_H  
  2. #define MYSTRING_H  
  3.   
  4. #include <string>  
  5.   
  6. using namespace std;  
  7.   
  8. class MyString  
  9. {  
  10. public:  MyString()
  11.     {  
  12.         m_ptr = nullptr;  
  13.     }  
  14.   
  15.     explicit MyString(const string str)
        {  
  16.         m_ptr = new string(str);  
  17.     }  
  18.   
  19.     MyString(const MyString& other)
       {  
  20.         if(other.m_ptr)  
  21.             m_ptr = new string(*other.m_ptr);  
  22.         else  
  23.             m_ptr = nullptr;  
  24.     }  
  25.   
  26.    MyString(MyString&& other)
       {  
  27.         m_ptr = other.m_ptr;  
  28.         other.m_ptr = nullptr;  
  29.     }  
  30.   
  31.     MyString& operator =(const MyString& other)
        {  
  32.         MyString(other).swap(*this);  
  33.         return *this;  
  34.     }  
  35.   
  36.     MyString& operator =(MyString&& other)
        {  
  37.         MyString(move(other)).swap(*this);  
  38.         return *this;  
  39.     }  
  40.   
  41.     ~MyString()
        {  
  42.         delete m_ptr;  
  43.     }  
  44.   
  45.     string get() const 
        {  
  46.         return m_ptr ? *m_ptr : 0;  
  47.     }  
  48.   
  49.     void swap(MyString& other) 
        {  
  50.         std::swap(m_ptr, other.m_ptr);  
  51.     }  
  52.   
  53. private:  
  54.     std::string *m_ptr;  
  55. };  
  56.   
  57. #endif // MYSTRING_H