Write IntArray with a raw buffer and all five special members (deep copy, noexcept moves via std::exchange, copy-and-swap assignment), plus push_back with growth; count copies and moves while using it.
#include <algorithm>
#include <iostream>
#include <utility>
class IntArray {
int* data_ = nullptr;
std::size_t size_ = 0, cap_ = 0;
public:
static inline int copies = 0, moves = 0;
IntArray() = default;
~IntArray() { delete[] data_; }
IntArray(const IntArray& o) : data_(o.cap_ ? new int[o.cap_] : nullptr), size_(o.size_), cap_(o.cap_) {
std::copy(o.data_, o.data_ + size_, data_);
++copies;
}
IntArray(IntArray&& o) noexcept
: data_(std::exchange(o.data_, nullptr)), size_(std::exchange(o.size_, 0)), cap_(std::exchange(o.cap_, 0)) { ++moves; }
IntArray& operator=(IntArray o) noexcept { swap(o); return *this; } // copy-and-swap: handles both
void swap(IntArray& o) noexcept { std::swap(data_, o.data_); std::swap(size_, o.size_); std::swap(cap_, o.cap_); }
void push_back(int v) {
if (size_ == cap_) {
std::size_t nc = cap_ ? cap_ * 2 : 4;
int* nd = new int[nc];
std::copy(data_, data_ + size_, nd);
delete[] data_;
data_ = nd; cap_ = nc;
}
data_[size_++] = v;
}
std::size_t size() const { return size_; }
int sum() const { int s = 0; for (std::size_t i = 0; i < size_; ++i) s += data_[i]; return s; }
};
IntArray range(int n) { IntArray a; for (int i = 1; i <= n; ++i) a.push_back(i); return a; }
int main() {
IntArray a = range(10); // returned local: elided or moved
IntArray b = a; // 1 copy
IntArray c;
c = std::move(b); // parameter moved in, then swapped
a = c; // parameter copied, then swapped
std::cout << a.sum() << ' ' << b.size() << ' ' << c.size() << " copies=" << IntArray::copies << '\n';
return 0;
}
55 0 10 copies=2
The by-value assignment operator serves as both copy and move assignment: it copies or moves into the parameter, then swaps. Only two real copies happen. (The move count is not printed because it depends on optional elision.)