# Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2005-10-15 09:29:05

On Oct 14, 2005, at 11:54 PM, Joel de Guzman wrote:

> Interesting point! Now consider this:
>
> int a = 1;
> int b = 2;
> tuple<int&> x(a);
> tuple<int&> y(b);
> swap(x, y);
>
> What happens after the swap? The same thing happens!
>
> before swap
> a: 1
> b: 2
> x: 1
> y: 2
> swap
> a: 2
> b: 2
> x: 2
> y: 2

It is on my to-do list to propose a specialized swap for tuple, as I
just did for pair:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/
n1856.html#20.2.3%20-%20Pairs

The effect of the general swap on both pair and tuple are disastrous in
the context of move semantics. Consider:

typedef pair<int, vector<int> > Pair;
Pair x, y;
...
swap(x, y);

If the general swap is used, this is an O(N) operation, but if instead
pair does:

swap(x.first, y.first);
swap(x.second, y.second);

then things just work, O(1). tuple should (will) have an analogous
swap (as does tr1::array already - another "tuple like" type). This is
already implemented in CodeWarrior Pro 10 (beta). The following:

#include <tuple>
#include <tupleio>
#include <iostream>

int main()
{
int a = 1;
int b = 2;
std::tr1::tuple<int&> x(a);
std::tr1::tuple<int&> y(b);
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
std::cout << "x: " << x << '\n';
std::cout << "y: " << y << '\n';
swap(x, y);
std::cout << "swap(x, y)\n";
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
std::cout << "x: " << x << '\n';
std::cout << "y: " << y << '\n';
}

Outputs:

a: 1
b: 2
x: (1)
y: (2)
swap(x, y)
a: 2
b: 1
x: (2)
y: (1)

So I'm not weighing in on either side of the optional<T&> debate at the
moment. All I'm saying is that any argument based on the current
behavior of swapping tuple<T&> is going to be false tomorrow (if I can