Home > Mobile >  dereferencing a pointer to set a value vs. assigning an address to the pointer?
dereferencing a pointer to set a value vs. assigning an address to the pointer?

Time:03-29

Could someone explain the difference between the following two snippets of code? In the function below, *frame_id maybe a nullptr, it's basically the output parameter in the function.

bool LRUReplacer::Victim(frame_id_t *frame_id) {
  long oldest_ts = std::numeric_limits<long>::max();
  for (auto & it : this->LRUCache){
    if (it.ts < oldest_ts){
      oldest_timestamp = it.ts;
      *frame_id = it.frame_id;
    }
  }

vs.

bool LRUReplacer::Victim(frame_id_t *frame_id) {
  long oldest_ts = std::numeric_limits<long>::max();
  for (auto & it : this->LRUCache){
    if (it.ts < oldest_ts){
      oldest_timestamp = it.ts;
      frame_id = &it.frame_id;
    }
  }

in the first case, we are assigning frame_id the value of it.frame_id and in the second case we are assigning the pointer the address of it.frame_id?

CodePudding user response:

Let's consider a simplified example doing basically the same as reading/writing/dereferencing is concerned:

void f1(int* value)
{
    *value = 1;
}

int g_value = 1;

void f2(int* value)
{
    value = &g_value;
}

int main()
{
    {
        int value = 2;
        f1(&value);
        std::cout << value << '\n'; // prints 1
    }


    {
        int value = 2;
        f2(&value);
        std::cout << value << '\n'; // prints 2
    }
}

Note that you just reassign the parameter in the second alternative. The parameter was a pointer value that was passed by value and therefore there is absolutely no effect for the variable the pointer the caller passed a points to.

In C using a reference is preferrable:

void f3(int& value)
{
    value = 1;
}

int main()
{
    int value = 2;
    f3(value);
    std::cout << value << '\n'; // prints 1
}

CodePudding user response:

The first one is replacing a value pointed to by frame_id with a new value. The second is trying to replace the given pointer, to make it point to something else. But it will not work.

You are given a pointer on the stack and resetting it. That's not going to get passed back to the caller. He is going to be stuck with the value he passed you. Unless you pass it by reference

If you wanted the second one to work you would need to change the signature to be this:

bool LRUReplacer::Victim(frame_id_t*& frame_id) {

CodePudding user response:

In the first loop, if it.ts < oldest_ts you will assign the value of it.frame_id to the frame_id_t to which frame_id points. After the loop is done, the frame_id_t instance (*frame_id) will hold the last value that was assigned to it.

In the second loop, you will instead assign the address of it.frame_id to the frame_id_t* (frame_id). After the loop is done, frame_id will point at the last it.frame_id it was set to point at.

  • Related