Hard
Prototype clone() built on the implicit copy constructor
What happens when this program runs?
main.cpp
struct Document {
virtual Document* clone() const = 0;
virtual ~Document() = default;
};
class Report : public Document {
public:
explicit Report(size_t n) : buffer_(new int[n]), size_(n) {}
~Report() override { delete[] buffer_; }
// naive clone(): compiler-generated-looking copy of the pointer, not the data
Document* clone() const override {
Report* copy = new Report(*this); // uses implicit copy ctor
return copy;
}
private:
int* buffer_;
size_t size_;
};
int main() {
Report original(100);
Document* copy = original.clone();
delete copy; // ~Report runs: delete[] buffer_ frees the SHARED buffer
} // original destructs here: delete[] buffer_ frees the SAME buffer again24 of 44 in Design Patterns