mercredi 18 mars 2020

C++ reference_wrapper vector fills with wrong values

I'm trying to use reference wrappers in C++, since I want to be able to directly alter objects' values, but their values are all wrong. Here's an example that demonstrates this problem:

#include <vector>
#include <functional>
#include <iostream>
using namespace std;

int main() {
    vector<int> v1 = {1, 2, 3};
    for (int i : v1) {
        cout << i << " ";
    }
    cout << endl;

    vector<reference_wrapper<int>> v2;
    for (int i : v1) {
        v2.push_back(i);
    }
    for (int i : v2) {
        cout << i << " ";
    }
}

It prints

1 2 3
3 3 3

I'm not sure why the reference wrapper vector v2 is not copying the referred values in v1...

Aucun commentaire:

Enregistrer un commentaire