c++stlsetreference-wrapper

reference_wrapper in c++ containers


Consider following snippet:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int x=3;
    int y=1;
    int z=2;
    cout<<(&x)<<' '<<(&y)<<' '<<(&z)<<endl;
    set<reference_wrapper<int>> a;
    a.insert(ref(x));
    a.insert(ref(y));
    a.insert(ref(z));
    for(const auto& i: a) cout<<i<<' '<<endl;
    y=10;
    for(const auto& i: a) cout<<i<<' ';
    return 0;
}

What would happen to underlying container when a property used by container for sorting is modified?


Edit1 : From what I can try by running code, ordering goes wrong but since it was holding a reference, value is correctly updated. So one should be careful when using reference_wrapper inside containers (specially where mutations can cause container to invalidate its assertions)?


Solution

  • What would happen to underlying container when a property used by container for sorting is modified?

    Any further use of the container, that requires the comparison of that element, has undefined behaviour, because you are violating this requirement:

    For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.

    [associative.reqmts.general]