Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

&rhs != this, compare a reference to a pointer?

this is an assignment operator. &rhs != this is confusing. my questions: rhs is a reference of Message type. What does &rhs mean? what does & do (a memory address of a reference?)? Another question is about return *this . since we want a reference to type Message, but *this is a Message typed object, right? How can we return an object to a reference?

Message& Message::operator=(const Message &rhs)
{
    if (&rhs != this)
    {
         some functions;
    }
    return *this;
}
like image 602
ihm Avatar asked May 21 '26 15:05

ihm


2 Answers

&rhs means address of the object which reference is referecing to.

Message a;
const Message &rhs = a;

if (&rhs == &a) std::cout << "true" << std::endl;

This is will print true.

A reference is not a different object; it is just a syntactic sugar of pointer, which points to the same object whose reference it is. So when you write return this, it returns a pointer to the object, but if you write return *this, it returns either a copy of the object, or reference to the object, depending on the return type. If the return type is Message &, then you tell the compiler that "don't make a copy and instead return the same object". Now the same object is nothing but a reference. A reference of an object can be made anytime. For example, see the declaration of rhs above; it is const Message & rhs = a, since the targer type is mentioned as reference type, you're making a reference rhs of the object a. It is that simple.

like image 100
Nawaz Avatar answered May 23 '26 04:05

Nawaz


Besides Nawaz's great answer, I want to point out that you have to be careful about returning a reference to a local variable which will go out of scope after function return. So avoid returning a reference like this:

string& foo()
{
    string result = "abc";
    return result;
}

which causes the following compiler warning:

reference to local variable result returned

like image 45
B Faley Avatar answered May 23 '26 05:05

B Faley