提问人:Vencat 提问时间:9/13/2019 最后编辑:Vencat 更新时间:11/3/2021 访问量:136
重载 “=” 运算符与自赋值检查 C++ 入门第 5 版 - 章节 - 13.4
Overloading "=" operator with self assignment check in C++ Primer 5th edition - Chapter - 13.4
问:
我正在关注 C++ 入门第 5 版,并对下面的“=”运算符重载与自我分配检查感到困惑。下面的 Message 类有两个成员变量,一组指向 Folder 对象的指针和一个消息字符串。
我的问题是,当我尝试自行分配消息对象(例如:m1 = m1)时,由于通过引用传递rhs参数并调用remove_from_Folders()函数,指向Folder对象(std::set folders)的指针集重置为零,但作者声明此实现将正确处理自赋值。
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++ 入门第 5 版 - 第 13.4 章。
如果有人在这方面帮助我,将不胜感激。
答: 暂无答案
评论
folder
this
rhs
if (this == &rhs) return *this;