Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #ifndef R_VALUE_REF
  2. #define R_VALUE_REF
  3.  
  4. class String {
  5. public:
  6. String(String&&); // Move ctor
  7. String(const String&); // Normal copy ctor
  8. ~String(); // Dtor
  9. void swap(String&); //Constant time swap
  10. String& operator= (String&&); // Move assignment
  11. String& operator= (const String&); // Normal assignment
  12.  
  13. private:
  14. int stringSize;
  15. char *str;
  16. };
  17.  
  18. #endif // !R_VALUE_REF
  19.  
  20.  
  21. #include "class.hpp"
  22.  
  23. String::String(const String& actual) { // Normal ctor
  24. stringSize = actual.stringSize;
  25. str = new char[stringSize];
  26. int i = 0;
  27. while (actual.str[i] != 0) {
  28. str[i] = actual.str[i];
  29. ++i;
  30. }
  31. str[i] = 0;
  32. }
  33.  
  34. String::String(String&& actual) { // Move ctor
  35. stringSize = actual.stringSize;
  36. str = actual.str;
  37. actual.str = 0;
  38. actual.stringSize = 0;
  39. }
  40.  
  41. String& String::operator=(const String& rhs) { // Normal assignment - Only called on l-values
  42. if (str == rhs.str) {
  43. return *this;
  44. }
  45. delete[] str;
  46. stringSize = rhs.stringSize;
  47. str = new char[stringSize];
  48. int i = 0;
  49. while (rhs.str[i] != 0) {
  50. str[i] = rhs.str[i];
  51. ++i;
  52. }
  53. str[i] = 0;
  54. return *this;
  55. }
  56.  
  57. String& String::operator=(String&& rhs) { // Move assignment - Only called on r-values
  58. swap(rhs);
  59. return *this;
  60. }
  61.  
  62. String::~String() {
  63. delete str;
  64. }
  65.  
  66. void String::swap(String& rhs) { // Constant time swap
  67. char *tmp = str;
  68. str = rhs.str;
  69. rhs.str = tmp;
  70. int temp = stringSize;
  71. stringSize = rhs.stringSize;
  72. rhs.stringSize = temp;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement