Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a vector of reference_wrapper<int>

Tags:

c++

clang

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?
like image 202
user423455 Avatar asked Nov 26 '25 05:11

user423455


2 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)
like image 78
Konrad Rudolph Avatar answered Nov 27 '25 19:11

Konrad Rudolph


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.

like image 41
sanitizedUser Avatar answered Nov 27 '25 19:11

sanitizedUser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!