jeudi 24 septembre 2015

One liner swapping using std::tie

In python we can swap two variables as

>>> a , b = b , a

We can do similar kind of swapping in C++11 as

void swap(int &a,int &b)
{
    std::tie(a,b) = std::make_tuple(b,a);
}

Above works fine, and at O3 generates similar assembly as

void swap(int &a,int &b)
{
    int c = a;
    a = b;
    b = c;
}

But my question is it conforming to standards or I am missing something? Or is it a fluke like...

a = (a+b) - (b=a);

Which has sequence point issue.

Aucun commentaire:

Enregistrer un commentaire