Created
May 8, 2016 22:05
-
-
Save JamesMenetrey/34e3ea73893cad952c904b7e9387a847 to your computer and use it in GitHub Desktop.
C/C++ - The perfect Copy-And-Swap idiom usage
This file contains hidden or 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
// Source: http://codereview.stackexchange.com/questions/95464/is-the-copy-swap-idiom-implemented-here-correctly | |
class Array | |
{ | |
int size; | |
int* data; | |
public: | |
Array(Array const& copy) | |
: size(copy.size) | |
, data(new int[size]) | |
{ | |
std::copy(copy.data, copy.data + size, data); | |
} | |
Array& operator=(Array copy) // Pass by value to implicitly do the copy. | |
{ | |
copy.swap(*this); // Copy has been. So just update the | |
return *this; // state of this object in an exception safe way. | |
} | |
void swap(Array& other) noexcept | |
{ // Swap content with no change of exception. | |
using std::swap; | |
swap(data, other.data); | |
swap(size, other.size); | |
} | |
// Other methods you would expect here. | |
}; | |
void swap(Array& lhs, Array& rhs) | |
{ | |
// I prefer to define my swap function in terms of the swap method. | |
// I just like all the work to be internal to the class. | |
// And this function becomes really trivial now. | |
// | |
// BUT | |
// | |
// See Emily L. answer for a more standard alternative | |
// Her (and I use the female her because of an assumption) | |
// answer would be a more normal alternative. | |
// and an overall better review. | |
lhs.swap(rhs); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment