Skip to content

Instantly share code, notes, and snippets.

@meshell
Created February 22, 2016 21:00
Show Gist options
  • Save meshell/9d04f257f1304ef752ff to your computer and use it in GitHub Desktop.
Save meshell/9d04f257f1304ef752ff to your computer and use it in GitHub Desktop.
Copy and Swap idiom
#include <cstring>
#include <iostream>
class foo
{
public:
explicit foo(const char* arg) : cstring{new char[std::strlen(arg)+1]} {
std::strcpy(cstring, arg);
}
~foo() {
delete[] cstring;
}
foo(const foo& other) : cstring{new char[std::strlen(other.cstring) + 1]} {
std::strcpy(cstring, other.cstring);
}
foo(foo&& other) noexcept : cstring{other.cstring} {
other.cstring = nullptr;
}
// Copy assignment and Move assignment
foo& operator=(foo other) // pass by value
{
std::swap(cstring, other.cstring);
return *this;
}
private:
char* cstring;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment