#include #include #include #include struct Values { std::vector items; }; class DeepBox { std::unique_ptr value_; public: explicit DeepBox(int value) : value_(new int(value)) {} DeepBox(const DeepBox& other) : value_(other.value_ ? new int(*other.value_) : nullptr) {} DeepBox& operator=(const DeepBox& other) { DeepBox temporary(other); value_.swap(temporary.value_); return *this; } DeepBox(DeepBox&&) noexcept = default; DeepBox& operator=(DeepBox&&) noexcept = default; ~DeepBox() = default; int value() const { return value_ ? *value_ : 0; } void set(int value) { if (value_) *value_ = value; else value_.reset(new int(value)); } }; int main() { Values a{{1, 2}}; Values b = a; b.items[0] = 8; assert(a.items[0] == 1); DeepBox original(3); DeepBox copy = original; copy.set(7); assert(original.value() == 3 && copy.value() == 7); original = original; DeepBox moved = std::move(copy); assert(original.value() == 3); assert(moved.value() == 7 && copy.value() == 0); }