Home > Software design >  C Modifying pointer in Range based for loop
C Modifying pointer in Range based for loop

Time:03-07

I tried to modify pointer of object in array like this.

array<unique_ptr<Object>, OBJ_SIZE> OtherList;  // All Object were allocated already.
array<Object*, OBJ_SIZE> ObjectList;

Object* GetPointerFromOtherList(int i) { return OtherList[i].get(); }

for(int i = 0; Object* obj : ObjectList)
{
     // Store pointer of pre-allocated object
     obj = GetPointerFromOtherList(i);
     i  ;
}

But when I access to this objects, it seems like it's empty.

for(Object* obj : ObjectList)
{
     // Access violation because obj is null.
     obj->doSomething();
}

I tried other way too.

for(int i = 0; auto& obj : ObjectList)
{
     // store pointer of pre-allocated object.
     obj = GetPointerFromOtherList(i);
     i  ;
}

and this work. The auto& keyword is same as Object*&. and I don't really understand why the first method didn't worked and second one worked otherwise. Can someone explain this to me?

CodePudding user response:

With Object* obj : ObjectList, obj is a copy of the pointer element of ObjectList. Assigning to that copy with obj = GetPointerFromOtherList(i); doesn't change anything in the container, since obj is just a completely independent variable.

With Object*& obj : ObjectList, obj is a reference to the pointer element in ObjectList. When you assign to it with obj = GetPointerFromOtherList(i);, you are assigning to the pointer element inside ObjectList.

  •  Tags:  
  • c
  • Related