1

This question is an extension of this question. I understand that due to push_back() new memory allocation takes place and the address of the first element of std::vector v changes but should not std::vector v2 change its address accordingly?

#include <memory>
#include <iostream>
#include <vector>
#include <functional>

int main()
{
    std::vector<int> v;
    std::vector<std::reference_wrapper<int>> v2;

    for (int i=0; i<3; ++i)
    {
        int b = i;

        v.push_back(b);
        v2.push_back(v.back());

        std::cout << "org: " << std::addressof(v[0]) << std::endl;
        std::cout << "ref: " << std::addressof(v2[0].get()) << std::endl;

    }

    return 0;
}

Output:

org: 0x605010
ref: 0x605030
org: 0x605050
ref: 0x605010
org: 0x605030
ref: 0x605070
4

1 回答 1

2

不,reference_wrapper 就像一个指针。当第一个vector重新分配时,内存中旧的int对象被销毁,reference_wrapper指向的int无效。现在使用它是一个错误。

于 2014-06-21T23:04:29.997 回答