Refinement return in C ++

0

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.

    
asked by anonymous 09.04.2018 / 05:04

2 answers

2

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? .

    
09.04.2018 / 05:34
2

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.
  • The -> and [] operators precede the & operator, so let's go to them.
    • The associativity of these two operators is left to right.
    • In this case this->data is a pointer to the data array.
    • E this->data[0] is an integer. The first element of the array data .
  • finally the & 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";
}
    
09.04.2018 / 07:00