What does -> mean in C++? [duplicate]
It's to access a member function or member variable of an object through a pointer, as opposed to a regular variable or reference.
For example: with a regular variable or reference, you use the .
operator to access member functions or member variables.
std::string s = "abc";
std::cout << s.length() << std::endl;
But if you're working with a pointer, you need to use the ->
operator:
std::string* s = new std::string("abc");
std::cout << s->length() << std::endl;
It can also be overloaded to perform a specific function for a certain object type. Smart pointers like shared_ptr
and unique_ptr
, as well as STL container iterators, overload this operator to mimic native pointer semantics.
For example:
std::map<int, int>::iterator it = mymap.begin(), end = mymap.end();
for (; it != end; ++it)
std::cout << it->first << std::endl;
a->b
means (*a).b
.
If a
is a pointer, a->b
is the member b
of which a
points to.
a
can also be a pointer like object (like a vector<bool>
's stub) override the operators.
(if you don't know what a pointer is, you have another question)
- Access operator applicable to (a) all pointer types, (b) all types which explicitely overload this operator
-
Introducer for the return type of a local lambda expression:
std::vector<MyType> seq; // fill with instances... std::sort(seq.begin(), seq.end(), [] (const MyType& a, const MyType& b) -> bool { return a.Content < b.Content; });
-
introducing a trailing return type of a function in combination of the re-invented
auto
:struct MyType { // declares a member function returning std::string auto foo(int) -> std::string; };