Skip to content

Instantly share code, notes, and snippets.

@oconnor663
Last active March 21, 2023 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oconnor663/3001a7914cb916da849dfdf669bdfaf7 to your computer and use it in GitHub Desktop.
Save oconnor663/3001a7914cb916da849dfdf669bdfaf7 to your computer and use it in GitHub Desktop.
C++ constructor/destructor squawker
#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
}
@oconnor663
Copy link
Author

oconnor663 commented Jul 16, 2021

Output:

constructor       a1
copy constructor  a1

constructor       b1
constructor       b2
copy assignment   b2 = b1

constructor       c1
move constructor  c1

constructor       d1
constructor       d2
move assignment   d2 = move(d1)

destructor        d1
destructor        <moved out of>
destructor        c1
destructor        <moved out of>
destructor        b1
destructor        b1
destructor        a1
destructor        a1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment