Skip to content

Instantly share code, notes, and snippets.

@dlmanning
Created November 20, 2019 19:19
Show Gist options
  • Save dlmanning/af1e0ca1c928078d4edc3127fc303ce4 to your computer and use it in GitHub Desktop.
Save dlmanning/af1e0ca1c928078d4edc3127fc303ce4 to your computer and use it in GitHub Desktop.
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Foo {
public:
Foo() {
cout << " "
<< "Foo::Foo() - (Constructor @ " << this << ")\n";
m_data = new uint8_t[m_length];
for (uint8_t i = 0; i < m_length; i++) {
m_data[i] = i;
}
}
Foo(const Foo& other) {
cout << " "
<< "Foo::Foo(const Foo&) - (Copy Constructor @ " << this << " <- " << &other << ")\n";
// Object is being constructed, so we need to allocate m_data
m_data = new uint8_t[m_length];
for (int i = 0; i < m_length; i++) {
m_data[i] = other.m_data[i];
}
}
Foo& operator=(const Foo& other) {
cout << " "
<< "Foo& Foo::operator=(const Foo&) - (Copy Assignment @ " << this << " <- " << &other
<< ")\n";
// Target already exists. No need to allocate m_date
for (int i = 0; i < m_length; i++) {
m_data[i] = other.m_data[i];
}
return *this;
}
Foo(Foo&& other) {
cout << " "
<< "Foo::Foo(Foo&&) - (Move Constructor @ " << this << " <- " << &other << ")\n";
m_data = other.m_data;
other.m_data = nullptr; // other is now in an undefined state
}
Foo& operator=(Foo&& other) {
cout << " "
<< "Foo& Foo::operator=(Foo&&) - (Move Assignment @ " << this << " <- " << &other << ")\n";
delete m_data; // release our existing resource
m_data = other.m_data;
other.m_data = nullptr; // other is now in an undefined state
return *this;
}
~Foo() {
cout << " "
<< "Foo::~Foo() - (Destructor @ " << this << ")\n";
if (m_data) delete m_data;
}
string toString() {
ostringstream out;
out << " ";
if (!m_data) {
out << "Empty\n";
} else {
out << '[';
for (int i = 0; i < m_length - 1; i++) {
out << static_cast<int>(m_data[i]) << ", ";
}
out << static_cast<int>(m_data[m_length - 1]) << "]\n";
}
return out.str();
}
private:
int m_length = 16;
uint8_t* m_data;
};
int main() {
cout << endl << "Foo f;\n" << endl;
Foo f;
cout << endl << "Foo g = f;\n" << endl;
Foo g = f; // Copy
cout << endl
<< "Foo h;\n"
<< "h = f;\n"
<< endl;
Foo h;
h = f; // Copy assignment
cout << endl << "Foo j = move(f);\n" << endl;
Foo j = move(f); // Move construction
cout << endl
<< "Foo k;\n"
<< "k = move(g);\n"
<< endl;
Foo k;
k = move(g);
cout << endl << "Content:\n";
cout << "f:" << f.toString();
cout << "g:" << g.toString();
cout << "h:" << h.toString();
cout << "j:" << j.toString();
cout << "k:" << k.toString();
cout << endl << "Leaving main\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment