Created
February 22, 2016 21:00
-
-
Save meshell/9d04f257f1304ef752ff to your computer and use it in GitHub Desktop.
Copy and Swap idiom
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 <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