Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Person {
- int age;
- char* name;
- friend void swap(Person& first, Person& second) /* nothrow */ {
- std::swap(first.name, first. name);
- std::swap(first.age, first.age);
- }
- public:
- // user-defined parameterized constructor
- Person(int age, char* name) : age(age) {
- this->name = new char[strlen(name)+1];
- strcpy(this->name, name);
- }
- // copy constructor
- Person(const Person& other) : age(other.age) {
- name = new char[strlen(other.name)+1];
- strcpy(name, other.name);
- }
- // copy assignment operator
- Person& operator=(const Person& other) {
- if (this != &that) {
- Person temp(other);
- swap(temp, other);
- }
- return *this;
- }
- // move constructor
- Person(Person&& other) noexcept : name(std::exchange(other.name, nullptr), age(other.age) {}
- // move assignment operator
- Person& operator=(Person&& other) {
- std::swap(name, other.name);
- std::swap(age, other.age);
- return *this;
- }
- // destructor
- ~Person() {
- delete[] name;
- }
- // alternatively we can combine both assignment operators and get rid of the custom swap function
- /*
- Person& operator=(Person other) {
- std::swap(name, other.name);
- std::swap(age, other.age);
- return *this;
- }
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement