// copy-constructor dumb_array(const dumb_array& other) : mSize(other.mSize), mArray(mSize ? newint[mSize] : nullptr) { // note that this is non-throwing, because of the data // types being used; more attention to detail with regards // to exceptions must be given in a more general case, however std::copy(other.mArray, other.mArray + mSize, mArray); }
// destructor ~dumb_array() { delete [] mArray; }
private: std::size_t mSize; int* mArray; };
写出他的拷贝赋值函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// the hard part dumb_array& operator=(const dumb_array& other) { if (this != &other) // (1) { // get rid of the old data... delete [] mArray; // (2) mArray = nullptr; // (2) *(see footnote for rationale)
// ...and put in the new mSize = other.mSize; // (3) mArray = mSize ? newint[mSize] : nullptr; // (3) std::copy(other.mArray, other.mArray + mSize, mArray); // (3) }
dumb_array& operator=(const dumb_array& other) { if (this != &other) // (1) { // get the new data ready before we replace the old std::size_t newSize = other.mSize; int* newArray = newSize ? newint[newSize]() : nullptr; // (3) std::copy(other.mArray, other.mArray + newSize, newArray); // (3)
// replace the old data (all are non-throwing) delete [] mArray; mSize = newSize; mArray = newArray; }
friendvoidswap(dumb_array& first, dumb_array& second)// nothrow { // enable ADL (not necessary in our case, but good practice) usingstd::swap;
// by swapping the members of two objects, // the two objects are effectively swapped swap(first.mSize, second.mSize); swap(first.mArray, second.mArray); }