Andres
Andres

Reputation: 213

Dynamically allocate elements in tuple

I have a simple question since I did not find it online.

Is it safe to modify the elements in a tuple if I pass it by reference like this, I put it like that to emulate what I do.

#include <functional>
#include <iostream>
#include <map>
#include <tuple>
#include <vector>

using namespace std;

template <typename... Args>
struct S {
  tuple<Args...> tup;             //my tuple to hold data types but empty initially

  auto& args() { return tup; }    //method to access my tuple
};


// some function that modifies my tuple
void foo(auto& tup) {
  std::get<0>(tup).resize(1000);
  std::get<1>(tup)[76] = 654;
  std::get<1>(tup)[453] = 6;
}

int main() {
  S<vector<int>, map<int, int>> s;     // my object

  foo(s.args());

  printf("vecSize = %d\n", std::get<0>(s.args()).size());
  printf("mapSize = %d\n", std::get<1>(s.args()).size());

  return 0;
}

The previous piece of code works well, but I am not entirely sure if the memory, allocated for this tuple and its elements, won't be corrupted eventually when implementing too many dynamic allocations, assuming that the whole memory does not reach the limit.

Upvotes: 0

Views: 567

Answers (1)

Mooing Duck
Mooing Duck

Reputation: 66922

S, it's member tuple, and its members (vector+map) exist as s for the lifetime of the main method. You pass a reference to the tuple to the function foo which modifies those fully-alive members safely. This is all 100% valid and safe. I do not see any undefined behavior, leaks, or dangling references anywhere.

Upvotes: 1

Related Questions