← Back to Pointers
Question 728
Shelf Move Leaves the Source Empty
Shelf Move Leaves the Source Empty
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 MOVE semantics: moving takes over the other shelf's array and leaves that shelf empty, so the two never try to delete the same books.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. Moving copies ONE pointer, the address of that array; the books themselves stay where they are. 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(Shelf&& other) noexcept; // take over other's array and count; leave other with nullptr and 0 Shelf& operator=(Shelf&& other) noexcept; // guard self-assignment, delete every book and the array this shelf holds, take over other's resources, empty other ~Shelf(); // delete every copy, then the array void print() const; // "Shelf (N books)" then every book on its own line, or "Empty shelf" alone when the count is 0`The driver never copies a shelf, so the copy constructor and copy assignment are not needed. It move-constructs a second shelf from the first and prints both, move-assigns the second into a shelf built with one book and prints both, then move-assigns a shelf to itself through a reference and prints it, which must not destroy anything. 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:
after move-construct: Empty shelf Shelf (2 books) #101 The Hobbit x3 #102 Dune x1 after move-assign: Empty shelf Shelf (2 books) #101 The Hobbit x3 #102 Dune x1 after self-move: 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.