Copy Assignment operator, const and reference.

In this exercise the swap function pretty much does the same thing (I think) for the copy assignment operator as it's proper definition.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Wrong way to define.
Message& Message::operator=(const Message &rhs)
{
    swap(*this, rhs);

    return *this;
}

//Proper definition.
Message& Message::operator=(const Message &rhs)
{
    remove_from_Folders();
    contents = rhs.contents;
    folders = rhs.folders;
    add_to_Folders(rhs);
    return *this;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void swap(Message &lhs, Message &rhs)
{
    using std::swap;

    for (auto f : lhs.folders)
        f->remMsg(&lhs);
    for (auto f : rhs.folders)
        f->remMsg(&rhs);

    swap(lhs.folders, rhs.folders);
    swap(lhs.contents, rhs.contents);

    for (auto f : lhs.folders)
        f->addMsg(&lhs);
    for (auto f : rhs.folders)
        f->addMsg(&rhs);
}


However, trying to pass rhs as the second argument in swap gives an error. Removing the const from the parameter in Message& Message::operator=(const Message &rhs) compiles the code.

Why is that?
Because the second parameter of the swap is not a const reference. You may not call functions that have a non-const reference parameter for a const reference argument.
The whole idea of swap is to modify both of its parameters, switching out their contents. Passing const reference seems to break that.
Const means read-only as far as I am aware of and if you are using a reference as a parameter then you are writing to that value so would be hard to write to a read-only value.
Topic archived. No new replies allowed.