C ++ Primer第5版-章-13.4

时间:2019-09-13 08:04:21

标签: c++ c++11 operator-overloading assignment-operator

我正在关注C ++入门手册第5版,并被“ =”运算符重载与自我赋值检查混淆。 Message 类下面有两个成员变量,一组指向Folder对象的指针和一个消息字符串。

我的问题是当我尝试自行分配消息对象(例如:m1 = m1)时,由于通过引用传递rhs参数并调用remove_from_Folders(),指向Folder对象(std :: set文件夹)的指针集重置为零。 )功能,但作者声明此实现将正确处理自分配。

class Message
{
friend class Folder;
private:
    std::set<Folder*> folders;
    std::string content;
    void add_to_folders(const Message&);
    void remove_from_Folders();
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第5版-第13.4章。
如果有人帮助我,我将不胜感激。

0 个答案:

没有答案
相关问题