vendredi 14 avril 2023

Using a member std::tuple to iterate through an object's member vectors

I'm trying to iterate through an object's member std::vectors, using a member std::tuple that contains the references of the member vectors.

A simple example would be like this:

#include <iostream>
#include <vector>
#include <tuple>
struct S {
    std::vector<int> a;
    std::vector<double> b;
    std::tuple<std::vector<int>&, std::vector<double>&> tup{a, b};
};
int main() {
    S s; 
    s.a = {2, 3};
    s.b = {5.1, 6.1};
    std::apply([&](auto&... v){
        ((std::cout << v.size()), ...);
    }, s.tup);
}

This works, but the problem is that if I assign the object s to an std container, the references tup is holding can be dangling references. Such as:

    std::map<int, S> myMap;
    myMap[3] = s; // s.a and s.b has been copied to different addresses.
    auto& v = std::get<0>(myMap.at(3).tup); // -> still refers to the previous s.a, not the copied one.

Is there any decent way to solve this problem? I want the references to refer to the newly copied members, not the original ones so that the member vectors of the new object can be iterated through using the member tuple.

(This question is being written after asking this question.)

Aucun commentaire:

Enregistrer un commentaire