How to avoid unnecessary copies when initializing vectors with variadic templates

78 Views Asked by At

In my project, I'm facing the initializing vectors with variadic template. However, I found that some unnecessary or unexpected copies could happen in follow code (in function create_elements and create_dummies).

#include <iostream>
#include <vector>
#include <any>

struct Dummy {
  int x;
  Dummy() = default;
  Dummy(Dummy&&) = default;
  Dummy(const Dummy& d) {
    x = d.x;
    static int count = 0;
    printf("copy dummy %d, times: %d\n", x, ++count);
  }
  Dummy(int x) : x(x) {}
};

template<typename... Comps> std::vector<std::any> create_elements (Comps&&... value) {
  return {std::make_any<Comps>(std::forward<Comps>(value))...};
}

template<typename... Dummies> std::vector<Dummy> create_dummies (Dummies&&... value) {
  return {std::forward<Dummies>(value)...};
}

int main() {
  create_dummies(Dummy(1));
  create_elements(Dummy(2));
  std::vector<Dummy> w;
  w.emplace_back(std::move(Dummy(3)));
  return 0;
}

In above example, after compiling and running will result in

copy dummy 1, times: 1
copy dummy 2, times: 2

, which means that create_elements and create_dummies call the copy constructor of Dummy. What I expect is that these two methods will have the same behaviors as the emplace_back solution (no copy called). What should I do, or why can't I do that? thanks!

0

There are 0 best solutions below