Search code examples
c++c++11stdvectormemory-addressreference-wrapper

reference_wrapper does not change addresses accordingly


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

Solution

  • No, the reference_wrapper is like a pointer. When the first vector reallocates, the old int object in memory is destroyed, and the int pointed to by the reference_wrapper is invalid. It is an error to use it now.