I can not understand what the following function returns.
int * begin(){ //
return &this->data[0];
}
Does such a function return the address of a reference? I did not understand very well.
I can not understand what the following function returns.
int * begin(){ //
return &this->data[0];
}
Does such a function return the address of a reference? I did not understand very well.
It returns a pointer, which is an address of some object. The operator &
takes an address from the object instead of picking up the object at Yes.
In case it returns the address of this
, which has a great chance of being a pointer or reference. Then I wonder if the intention was not to return this
itself.
There must be some confusion because the statement &
indicates that something is a reference, but depending on the context the same symbol is the operator is something quite different, even though it has a relation.
Understand What is the difference between pointer and reference? .
There may be other possibilities. But one of them is a pointer to the first element of the array data
of the object of a class that implements the member function begin()
.
this
refers to the pointer to the object whose function is being called. ->
and []
operators precede the &
operator, so let's go to them.
this->data
is a pointer to the data
array. this->data[0]
is an integer. The first element of the array data
. &
operator returns the address of the integer this->data[0]
. Note that in this case, this->data
and &this->data[0]
return the same value.
One possible implementation:
#include <iostream>
struct s {
s() : data{1, 2, 3} {};
int *begin() { return &this->data[0]; };
int data[3];
};
int main() {
s var;
std::cout << *var.begin() << "\n";
}