Last active
March 21, 2023 04:22
-
-
Save oconnor663/3001a7914cb916da849dfdf669bdfaf7 to your computer and use it in GitHub Desktop.
C++ constructor/destructor squawker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
class Squawker { | |
public: | |
Squawker(string name) : name(name) { | |
cout << "constructor " << name << "\n"; | |
} | |
~Squawker() { | |
cout << "destructor " << name << "\n"; | |
} | |
Squawker(const Squawker &other) : name(other.name) { | |
cout << "copy constructor " << name << "\n"; | |
} | |
Squawker &operator=(const Squawker &other) { | |
cout << "copy assignment " << name << " = " << other.name << "\n"; | |
name = other.name; | |
return *this; | |
} | |
Squawker(Squawker &&other) : name(move(other.name)) { | |
cout << "move constructor " << name << "\n"; | |
other.name = "<moved out of>"; // for clarity | |
} | |
Squawker &operator=(Squawker &&other) { | |
cout << "move assignment " << name << " = move(" << other.name << ")\n"; | |
name = move(other.name); | |
other.name = "<moved out of>"; // for clarity | |
return *this; | |
} | |
private: | |
string name; | |
}; | |
int main() { | |
// constructor | |
Squawker a1 = {"a1"}; | |
// copy constructor | |
Squawker a2 = a1; | |
cout << "\n"; | |
// constructor | |
Squawker b1 = {"b1"}; | |
// constructor | |
Squawker b2 = {"b2"}; | |
// copy assignment | |
b2 = b1; | |
cout << "\n"; | |
// constructor | |
Squawker c1 = {"c1"}; | |
// move constructor | |
Squawker c2 = move(c1); | |
cout << "\n"; | |
// constructor | |
Squawker d1 = {"d1"}; | |
// constructor | |
Squawker d2 = {"d2"}; | |
// move assignment | |
d2 = move(d1); | |
cout << "\n"; | |
// all destructors run at end of scope | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: