jeudi 26 janvier 2017

Different behavior when trying to swap two variables using {} and std::make_pair()

I was trying to swap two variables using std::tie() as per the following code (I am aware of std::swap, I was just trying this out of curiosity):

#include <iostream>
#include <tuple>

using std::cin; using std::tie; 
using std::cout; using std::endl;
using std::make_pair;

int main() {
    int a = 2, b = 10;
    cout << "Before Swapping using {}" << endl;
    cout << "a: " << a << " b: " << b < <endl;
    tie(a, b) = {b, a};
    cout << "After Swapping using {}" << endl;
    cout << "a: " << a << " b: " << b << endl;

    a = 2, b = 10;
    cout << "Before Swapping using make_pair()" << endl;
    cout << "a: " << a << " b: " << b << endl;
    tie(a, b) = make_pair(b, a);
    cout << "After Swapping using make_pair()" << endl;
    cout << "a: " << a << " b: " << b << endl;    

    return 0;
}

I compiled it using g++ test.cpp -std=c++11 -o test.

But the output was this:

Before Swapping using {}
a: 2 b: 10
After Swapping using {}
a: 10 b: 10
Before Swapping using make_pair()
a: 2 b: 10
After Swapping using make_pair()
a: 10 b: 2

So, my question is, since we can write {a, b} instead of writing std::make_pair(a, b) everytime (C++11 onwards), why are these two versions giving different output?

My guess was that the following line

std::tie(a, b) = {b, a};

is not making a pair and for some reason only mutating the value of a. But I am not sure.

Aucun commentaire:

Enregistrer un commentaire