简体   繁体   English

指向类数据成员的指针

[英]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 << &(bv) << "\\n"; while (true); return 0; } 

I actually expected to see ten different addresses repeated 2 times 我实际上希望看到十个不同的地址重复2次

In this range based for loop : 在此范围内的for循环:

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

b is a copy of the element in the vector. b是向量中元素的副本。 Thats why you see 10 times the same adress. 这就是为什么您看到10倍相同地址的原因。 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. 这里b是对向量中元素的引用。

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 ). 使用vector::emplace_back ,您可以在构造过程中看到向量内部的地址(请参阅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";
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM