简体   繁体   中英

Why changing the reference of a pointer doesn't change it's original value?

I feel I miss some key concepts about references and pointers; I have the code like this

#include "stdio.h"
struct bar {};
class foo {
  public:
    foo(){
      barPtr = new bar();
    };
    bar* barPtr;

    bar*& getBarPtr() {
      return barPtr;
    };

};

int main() {
  foo fObject;
  bar* b = nullptr;

  b = fObject.getBarPtr();
  printf("B before updates %p\n", b);
  printf("barPtr before b updates %p\n", fObject.barPtr);

  b = new bar();
  printf("B after updates %p\n", b);
  printf("barPtr after b updates %p\n", fObject.barPtr);
  return 0;
}

The output is

b before updates 0x55db559ace70
barPtr before b updates 0x55db559ace70
b after updates 0x55db559ad2a0
barPtr after b updates 0x55db559ace70

What I want to achieve is changing what barPtr points to by using b , so I make getBarPtr function returns the reference of barPtr . What I don't understand is why changing b doesn't change barPtr .

Change your definition of b to:

bar*& b = fObject.getBarPtr();

What you are currently doing is copying the pointer of fObject into b : they are two independent objects. They have the same value (the address that points to the bar object you created in foo 's constructor), but they are not related to each other. So if you assign a new value to b , you will overwrite it, without fObject 's barPtr changing.

b and barPtr are two pointers to the same object in memory. Once you assign a new value to b , it just means it will point to a different object - as you've seen, it won't affer barPtr .

If you had modified the object itself (eg, doing something like barPtr->modifyMyData() ), you would have seen the modified value from both pointers.

Why do you think by changing the pointer-variable b, the class instance will be changed? You won't change it this way.

You have allocated two different pointer variables, one in the class foo and one outside: b;

You could use a pointer to pointer. And return the reference to the class's pointer and then change the content of this reference.

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