fork download
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. class String {
  5. public:
  6. String() = default;
  7. String(const char* string) {
  8. printf("Created\n");
  9. m_Size = strlen(string);
  10. m_Data = new char[m_Size];
  11. memcpy(m_Data, string, m_Size);
  12. }
  13.  
  14. String(const String& other) {
  15. printf("Copied\n");
  16. m_Size = other.m_Size;
  17. m_Data = new char[m_Size];
  18. memcpy(m_Data, other.m_Data, m_Size);
  19. }
  20.  
  21. // Move constructor
  22. String(String&& other) noexcept {
  23. printf("Moved!\n");
  24. m_Size = other.m_Size;
  25. m_Data = other.m_Data;
  26.  
  27. // Create an hollow object
  28. other.m_Size = 0;
  29. other.m_Data = nullptr;
  30. }
  31.  
  32. ~String() {
  33. printf("Destroyed\n");
  34. delete m_Data;
  35. }
  36.  
  37. void Print() {
  38. for (uint32_t i = 0; i < m_Size; i++)
  39. printf("%c", m_Data[i]);
  40. printf("\n");
  41. }
  42.  
  43. private:
  44. char* m_Data;
  45. uint32_t m_Size;
  46. };
  47.  
  48.  
  49. class Entity {
  50. public:
  51. Entity(const String& name) :
  52. m_Name(name) {}
  53.  
  54. // Move constructor
  55. Entity(String&& name) : m_Name(std::move(name)) {}
  56. // Entity(String&& name) : m_Name((String&&)name) {}
  57.  
  58. void PrintName() {
  59. m_Name.Print();
  60. }
  61.  
  62. private:
  63. String m_Name;
  64. };
  65.  
  66. int main() {
  67. Entity entity(String("Cherno"));
  68. entity.PrintName();
  69.  
  70. std::cin.get();
  71. }
  72.  
Success #stdin #stdout 0.01s 5412KB
stdin
Standard input is empty
stdout
Created
Moved!
Destroyed
Cherno
Destroyed