← Back to Pointers
Question 727
Shelf Deep Copy With a Self-Assignment Guard
Shelf Deep Copy With a Self-Assignment Guard
Bookis written for you; leave it alone. Write the classShelf, which owns copies of books in aconst Book**array (each element points to aBookthe shelf created withnew), and give it the copy constructor and copy assignment operator that such ownership demands.m_booksis a pointer to an array of pointers: the array itself comes fromnew const Book*[n], and each element holds the address of oneBook. A deep copy therefore needs a new array AND a newBookfor every slot. Write every loop inside the special member that needs it; do not add private helper functions. Private members:const Book** m_books;andsize_t m_count;Public interface used by the hidden driver: ``Shelf(const Book* books[], size_t count); // store a new copy of every book Shelf(const Shelf& other); // deep copy: its own array AND its own copies of the books Shelf& operator=(const Shelf& other); // guard against self-assignment, delete every book and the array this shelf holds, then deep copy ~Shelf(); // delete every copy, then the array size_t size() const; const Book& at(size_t index) const; // the book in that slot void print() const; // "Shelf (N books)" then every book on its own line`The driver copy-constructs a second shelf from the first and prints whether the two shelves hold the SAME object in slot 0 (comparing the addresses ofat(0)), assigns the first shelf into a shelf built with a different count, assigns a shelf to itself through a reference, and prints the shelves. A shallow copy shows up assharedand as a double delete under the leak check. For the input:`2 101 3 The Hobbit 102 1 Dune`` the exact output is what is shown in Expected Output. Free the memory you allocate — this question checks for memory leaks. Do NOT write a main function.
Expected Output:
copy: 2 books, separate assigned: 2 books, separate self: 2 books Shelf (2 books) #101 The Hobbit x3 #102 Dune x1
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
Pointers
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.