简体   繁体   中英

What is “operator->()” in C++?

I came across a C++ code that has something like operator->() being called. Below is the code snippet, should someone please explain it.

template <typename T>
bool List<T>::operator == (const List& rhs)const
{
  return (this == &rhs) || (root_.operator->() == rhs.root_.operator->());
}

Please note that root_ is object of another class of which full code is not available to me.

EDIT: I just explored the code and found that root_ is actually a custom implementation of a smart pointer. It has operator -> overloaded in it to dereference the smart pointer and get the actually pointer's value.

When you have an object, you can access its attributes via object.attr . When you have a pointer, you can access the attributes of the object it's pointing on by using the -> operator like so: ptr->attr .

So far this is the default behavior in C. However, the -> operator can be overloaded - ie, overridden like any function can. You can define your own behavior for a class so that object-> will mean whatever you want. However, I don't believe that in this context, the operator was overloaded. The weird syntax is because you can't just do this:

if lhs-> == rhs->

Since the -> operator must be followed by something. So the way to do it is to use the explicit, no-sugar, name for this function, ie, operator-> , and call it like a function (hence the parenthesis).

So:

return (this == &rhs) || (root_.operator->() == rhs.root_.operator->());

This line's meaning is "return true if the my object equals to the object on the left or if our _root attributes point to objects which are equal among themselves.".

What you're asking about is called the Structure dereference operator : T::operator ->(); It comes from , and in it can be overloaded.

It selects an element through pointer and used in the way it is used in your example it simply returns the address of the instance ( root_ ).

The address is then used to compare identity of instances (do the addresses match?)

它是类的->运算符的重载调用。

Usually operator->() returns a pointer, so this code is just comparing two pointers. I think it's a linked list implementation, and operator== compares pointers to entire list and pointers to head (root) element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM