vendredi 13 septembre 2019

Overloading "=" operator with self assignment check in C++ Primer 5th edition - Chapter - 13.4

I'm following C++ primer 5th edition and get confused by below "=" operator overloading with self assignment check. Below Message class has two member variables, a set of pointers to Folder objects and a message string.

My question is when I try to self assign a message object (example : m1 = m1) the set of pointer to Folder objects (std::set folders) reset to zero because of passing rhs parameter by reference and calling remove_from_Folders() function, but the author state that this implementation will handles self assignment correctly.

class Message
{
friend class Folder;
private:
    std::set<Folder*> folders;
    std::string content;
    void add_to_folders(const Message&);
    void remove_from_folder();
public:
    explicit Message(const std::string str="");
    Message(const Message&);
    Message& operator=(const Message&);
    ~Message();
};

Message& Message::operator=(const Message &rhs)
{    
    // handle self-assignment by removing pointers before inserting them    
    remove_from_Folders();   // update existing Folders    
    contents = rhs.contents; // copy message contents from rhs    
    folders = rhs.folders;   // copy Folder pointers from rhs    
    add_to_Folders(rhs);     // add this Message to those Folders    
    return *this;
}

void Message::remove_from_Folders()
{    
    for (auto f : folders) // for each pointer in folders
        f->remMsg(this);   // remove this Message from that Folder
    folders.clear();       // no Folder points to this Message
}

C++ Primer 5th edition - Chapter - 13.4.
It would be really appreciated, if anyone help me on this.

Aucun commentaire:

Enregistrer un commentaire