Treycos Treycos - 14 days ago 5
C++ Question

Pointer to class data member

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

Answer

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";
    ...
}
Comments