Skip to content

Instantly share code, notes, and snippets.

@meshell
Last active February 22, 2016 20:54
Show Gist options
  • Save meshell/5f6cb1802a7a6eaf2844 to your computer and use it in GitHub Desktop.
Save meshell/5f6cb1802a7a6eaf2844 to your computer and use it in GitHub Desktop.
Rule of Five
#include <cstring>
#include <iostream>
class foo
{
public:
// Constructor
explicit foo(const char* arg) : cstring{new char[std::strlen(arg)+1]}
{
std::strcpy(cstring, arg);
std::cout << "constructed\n";
}
// Destructor
~foo() {
delete[] cstring;
std::cout << "destructed\n";
}
// Copy constructor
foo(const foo& other) : cstring{new char[std::strlen(other.cstring) + 1]}
{
std::strcpy(cstring, other.cstring);
std::cout << "copy constructed\n";
}
// Move constructor
foo(foo&& other) noexcept : cstring{std::move(other.cstring)}
{
other.cstring = nullptr;
std::cout << "move constructed\n";
}
// Copy assignment
foo& operator=(const foo& other) {
foo tmp{other}; // re-use copy-constructor
*this = std::move(tmp); // re-use move-assignment
std::cout << "copy assigned\n";
return *this;
}
// move assignment
foo& operator=(foo&& other) noexcept {
delete[] cstring;
cstring = std::move(other.cstring);
other.cstring = nullptr;
std::cout << "move assigned\n";
return *this;
}
private:
char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment