'C++ Modifying pointer in Range based for loop

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?

c++


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source