A swap Function for Message

The library defines versions of swap for both string and set9.2.5, p. 339). As a result, our Message class will benefit from defining its own version of swap. By defining a Message-specific version of swap, we can avoid extraneous copies of the contents and folders members.

However, our swap function must also manage the Folder pointers that point to the swapped Messages. After a call such as swap(m1, m2), the Folders that had pointed to m1 must now point to m2, and vice versa.

We’ll manage the Folder pointers by making two passes through each of the folders members. The first pass will remove the Messages from their respective Folders. We’ll next call swap to swap the data members. We’ll make the second pass through folders this time adding pointers to the swapped Messages:

void swap(Message &lhs, Message &rhs)
{
    using std::swap; // not strictly needed in this case, but good habit
    // remove pointers to each Message from their (original) respective Folders
    for (auto f: lhs.folders)
        f->remMsg(&lhs);
    for (auto f: rhs.folders)
        f->remMsg(&rhs);
    // swap the contents and Folder pointer sets
    swap(lhs.folders, rhs.folders);     // uses swap(set&, set&)
    swap(lhs.contents, rhs.contents);   // swap(string&, string&)
    // add pointers to each Message to their (new) respective Folders
    for (auto f: lhs.folders)
        f->addMsg(&lhs);
    for (auto f: rhs.folders)
        f->addMsg(&rhs);
}


Exercises Section 13.4

Exercise 13.33: Why is the parameter to the save and remove members of Message a Folder&? Why didn’t we define that parameter as Folder? Or const Folder&?

Exercise 13.34: Write the Message class as described in this section.

Exercise 13.35: What would happen if Message used the synthesized versions of the copy-control members?

Exercise 13.36: Design and implement the corresponding Folder class. That class should hold a set that points to the Messages in that Folder.

Exercise 13.37: Add members to the Message class to insert or remove a given Folder* into folders. These members are analogous to Folder’s addMsg and remMsg operations.

Exercise 13.38: We did not use copy and swap to define the Message assignment operator. Why do you suppose this is so?


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.200.3