#include <algorithm> // std::copy#include <cstddef> // std::size_t
class dumb_array{public:// (default) constructordumb_array(std::size_t size = 0): mSize(size),mArray(mSize ? new int[mSize]() : nullptr){}
// copy-constructordumb_array(const dumb_array& other): mSize(other.mSize),mArray(mSize ? new int[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, howeverstd::copy(other.mArray, other.mArray + mSize, mArray);}
// destructor~dumb_array(){delete [] mArray;}
private:std::size_t mSize;int* mArray;};
这个类几乎成功地管理了数组,但它需要operator=才能正常工作。
失败的解决方案
以下是一个简单的实现可能看起来的样子:
// the hard partdumb_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 newmSize = other.mSize; // (3)mArray = mSize ? new int[mSize] : nullptr; // (3)std::copy(other.mArray, other.mArray + mSize, mArray); // (3)}
return *this;}
dumb_array& operator=(const dumb_array& other){if (this != &other) // (1){// get the new data ready before we replace the oldstd::size_t newSize = other.mSize;int* newArray = newSize ? new int[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;}
return *this;}
class dumb_array{public:// ...
friend void swap(dumb_array& first, dumb_array& second) // nothrow{// enable ADL (not necessary in our case, but good practice)using std::swap;
// by swapping the members of two objects,// the two objects are effectively swappedswap(first.mSize, second.mSize);swap(first.mArray, second.mArray);}
// ...};
void fs(std::vector<T, A> & a, std::vector<T, A> & b){a.swap(b);b.clear(); // not important what you do with b}
void fm(std::vector<T, A> & a, std::vector<T, A> & b){a = std::move(b);}