0

I wonder about two things.
1. Is moving std::tuple worth implementing? For example for std::tuple<int, int, int> would we gain anything? Would it be faster than copying or passing by reference?
2. In example given below, is there any real difference between those two?

void print_tuple(const std::tuple<int&&, int&&, int&&> position)
{
    int x = std::get<0>(position);
    int y = std::get<1>(position);
    int z = std::get<2>(position);

    std::cout << "x: " << x << " y: " << y << " z: " << z << std::endl;
}

void print_tuple(const std::tuple<int, int, int>&& position)
{
    int x = std::get<0>(position);
    int y = std::get<1>(position);
    int z = std::get<2>(position);

    std::cout << "x: " << x << " y: " << y << " z: " << z << std::endl;
}

int main()
{
    print_tuple(std::forward_as_tuple(1, 2, 3));
    print_tuple(std::move(std::tuple<int, int, int>(4, 5, 6)));
    //...
}
David G
  • 94,763
  • 41
  • 167
  • 253
Chris
  • 839
  • 1
  • 12
  • 30
  • 2
    Regarding your second question, it's quite easy to find out: Build (with optimizations enabled) and compare the generated code. You can easily do it online using e.g. https://godbolt.org/ – Some programmer dude Jul 02 '18 at 21:16

2 Answers2

0
  1. Apparently, moving std::tuple can give a huge speedup. Imagine copying a std::make_tuple(std::vector<int>(1000000, 0)¸ std::string(23456, 'H')). For std::tuple<int, int, int> moving won't be any different from copying. So,

  2. For a tuple as simple as that of three ints, you can pass it by a constref; or by value at all, especially when actual argument is a temporary.

bipll
  • 11,747
  • 1
  • 18
  • 32
0

std::tuple already supports move semantics, and so the transfer of data is already handled. If you wanted to store your own class types you would need to implement move semantics for your class, otherwise you would experience a copy operation for any type within your tuple.

The compiler might optimize out move for primitive types such as an integer, although it's not the low level detail that I would be familiar with.

You could look at implementing the following if you want to support your own class types:

class MyClass
{
    MyClass(MyClass&& m);
    MyClass& operator =(MyClass&& m);
};