...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <cstring> class IntArray { int *array; std::size_t nElems; public: // ... ~IntArray() { delete[] array; } IntArray(const IntArray& that); // nontrivial copy constructor IntArray& operator=(const IntArray &rhs) { if (this != &rhs) { delete[] array; array = nullptr; nElems = rhs.nElems; if (nElems) { array = new int[nElems]; std::memcpy(array, rhs.array, nElems * sizeof(*array)); } } return *this; } // ... }; |
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <cstring>
class IntArray {
int *array;
std::size_t nElems;
public:
// ...
~IntArray() {
delete[] array;
}
IntArray(const IntArray& that); // nontrivial copy constructor
IntArray& operator=(const IntArray &rhs) {
int *tmp = nullptr;
if (rhs.nElems) {
tmp = new int[rhs.nElems];
std::memcpy(tmp, rhs.array, nElems * sizeof(*array));
}
delete[] array;
array = tmp;
nElems = rhs.nElems;
return *this;
}
// ...
};
|
...