Search code examples
c++c++11structc++17swap

Is there a way to swap 2 structs?


In c++ you can swap 2 numbers without 3rd variable:

int x = 10;
int y = 5;
x ^= y; 
y ^= x; 
x ^= y; //x = 5, y = 10

So I wonder if there is a similar way to swap 2 structs without 3rd variable:

struct Position{int x, y;};
int main()
{
   Position firstPose{x = 10, y = 5;};
   Position secPose{x = 5, y = 10;};
   //Now I want to swap firstPose with secPose.
}

Is this possible? if so; how to do it


Solution

  • There is no a standard way to swap two structure without an intermediate copy. Arguably, one of the main benefit of swap "is" the intermediate copy, this wonderful article explain how swap is a crucial part to achieve "strong exception guarantee". https://www.stroustrup.com/except.pdf

    Furthermore, if the goal is to not make a copy of the struct (because is resource intensive) you can design your class using the pimpl idiom and swap just the pointer (you will still have a third variable but it will be just the raw pointer to the structure).

    If you want to use C++ effectively make yourself familiar with exception safety, it is truly of of the area where the language gives its best

    A bit old but still good article: http://www.gotw.ca/gotw/008.htm

    At the end, the final solution is create a custom swap function:

    #include <iostream>
    #include <string>
    
    struct Position{int x, y;};
    
    void swap(Position& a, Position& b)
    {
        a.x ^= b.x; 
        b.x ^= a.x; 
        a.x ^= b.x;
    
        a.y ^= b.y; 
        b.y ^= a.y; 
        a.y ^= b.y; 
    }
    
    int main()
    {
        Position a = { 10, 100};
        Position b = { 20, 200};
      
        swap(a, b);
        std::cout << "a:" << a.x << "," << a.y << std::endl;
        std::cout << "b:" << b.x << "," << b.y << std::endl;
    }
    

    IMHO, the last option is more for personal amusement than real production code.