0

In this little test program, can someone explain me:

  • Why is every addresses printed in both loops the same?
  • Why is it different from one loop to another?

    struct A {
        A(){ std::cout << &v << "\n"; };
        int v;
    };
    
    int main()
    {
        std::vector<A> vec;
    
        int i = 10;
        while (i--)
            vec.push_back(A());
    
        for (A b : vec)
            std::cout << &(b.v) << "\n";
    
        while (true);
        return 0;
    }
    

I actually expected to see ten different addresses repeated 2 times

Treycos
  • 7,373
  • 3
  • 24
  • 47

2 Answers2

1

In this range based for loop :

    for (A b : vec)
        std::cout << &(b.v) << "\n";

b is a copy of the element in the vector. Thats why you see 10 times the same adress. It is different for two different loops, because that copy happens to be in a different memory location. You probably wanted this:

    for (A& b : vec)
        std::cout << &(b.v) << "\n";

here b is a reference to the element in the vector.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

If you want to see the same addresses you need to look at the addresses inside the vector and not the addresses of temporary copies.

With vector::emplace_back, you can see the addresses inside the vector during the construction (see emplace_back). A reference access gives you the address inside the vector during the iterations.

int main()
{
    std::vector<A> vec;

    int i = 10;
    while (i--)
        vec.emplace_back();

    for (const A& b : vec)
        std::cout << &(b.v) << "\n";
    ...
}
Community
  • 1
  • 1
Franck
  • 1,635
  • 1
  • 8
  • 11