Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. class Person {
  2. int age;
  3.   char* name;
  4.  
  5. friend void swap(Person& first, Person& second) /* nothrow */ {
  6.   std::swap(first.name, first. name);
  7. std::swap(first.age, first.age);
  8.   }
  9.  
  10. public:
  11.  
  12. // user-defined parameterized constructor
  13.   Person(int age, char* name) : age(age) {
  14.   this->name = new char[strlen(name)+1];
  15.   strcpy(this->name, name);
  16.   }
  17.  
  18. // copy constructor
  19.   Person(const Person& other) : age(other.age) {
  20. name = new char[strlen(other.name)+1];
  21.   strcpy(name, other.name);
  22.   }
  23.  
  24. // copy assignment operator
  25.   Person& operator=(const Person& other) {
  26.   if (this != &that) {
  27.   Person temp(other);
  28.   swap(temp, other);
  29. }
  30.   return *this;
  31.   }
  32.  
  33. // move constructor 
  34.   Person(Person&& other) noexcept : name(std::exchange(other.name, nullptr), age(other.age) {}
  35.  
  36. // move assignment operator 
  37.  Person& operator=(Person&& other) {
  38.   std::swap(name, other.name);
  39.   std::swap(age, other.age);
  40.   return *this;
  41.  }
  42.  
  43. // destructor
  44.   ~Person() {
  45.   delete[] name;
  46.   }
  47.  
  48. // alternatively we can combine both assignment operators and get rid of the custom swap function
  49.   /*
  50.   Person& operator=(Person other) {
  51.   std::swap(name, other.name);
  52.   std::swap(age, other.age);
  53.   return *this;
  54.   }
  55.   */
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement