Printing a vector of reference_wrapper<int>

Viewed 141

I have the following test code that's runnable under clang.

#include <algorithm>
#include <vector>
#include <iostream>

int main() {

    std::vector<int> vs{1, 2, 4, 5};

    std::vector<std::reference_wrapper<int>> vs1;

    for (int i : vs) {
        std::cout << "loop: " << i << std::endl;
        vs1.emplace_back(i);
    }

    for (auto p : vs1) {
        std::cout << p << std::endl;
    }
    return 0;
}

You can plug that into https://rextester.com/l/cpp_online_compiler_clang (or locally). The result is:

loop: 1
loop: 2
loop: 4
loop: 5
5
5
5
5
  1. I'd expect 1,2,4,5, not 5 all the way.
  2. The code won't work on non-clang. Where's the problem?
3 Answers

i is a local variable inside its declaring for loop. It is a copy of each int in the vs vector. You are thus (via the emplace_back() call) creating reference_wrapper objects that refer to a local variable, keeping the references alive after the lifetime of the referred-to variable (i) has ended. This is undefined behavior.

The fix is to make i be a reference to each int, not a copy, that way the reference_wrappers refer to the ints in vs as expected:

for (int& i : vs)

First, you forgot <functional> header. Second, reference_wrapper<int> stores reference to an int. Not its value. So in this loop:

for (int i : vs) {
    std::cout << "loop: " << i << std::endl;
    vs1.emplace_back(i);
}

You are changing value of i but not its place in memory. It is always the same variable. That's why it prints the last value stored in that variable, which is 5.

You may imagine this range- based for loop

for (int i : vs) {
    std::cout << "loop: " << i << std::endl;
    vs1.emplace_back(i);
}

the following way

for ( auto first = vs.begin(); first != vs.end(); ++first )
{
    int i = *first;
    vs1.emplace_back(i);
}

that is within the loop you are dealing with the local variable i that will not be alive after exiting the loop.

You need to use a reference to elements of the vector like

for (int &i : vs) {
    std::cout << "loop: " << i << std::endl;
    vs1.emplace_back(i);
}
Related