Search code examples
c++swapunique-ptr

Does unique_ptr swap copy contents?


I have a class C with multiple member variables and I'm programmig a binary heap whose elements are of the type std::unique_ptr. For the reordering of elements in the heap, I'm currently calling std::swap(x,y) where x and y are references to unique_ptr.

I'm a bit confused with the explanation of this function on cplusplus.com and therelike.

https://www.cplusplus.com/reference/memory/unique_ptr/swap-free/

https://www.cplusplus.com/reference/memory/unique_ptr/swap/

My question is: Do these specifications of std::swap reassign pointer addresses or do they indeed do a tedious copy of the contents in x and y every time I call std::swap?

I'm asking because I could also redesign this thing and let the heap elements be just indices. These indices refer to vector entries that store the actual content. Then, a swap in the heap would just exchange two size_t's (instead of big elements of the class C) and the thing would work.

Thank you in advance.


Solution

  • std::swap(x, y) swaps the contents of variables x and y.

    If x and y are unique_ptrs then it swaps the contents of the unique_ptr variables. A unique_ptr variable holds a pointer, not a whole object. Since the pointers were swapped, now y points to the address that x used to point to and x points to the address that y used to point to.

    In other words it's the same as:

    unique_ptr<whatever> temp = std::move(x);
    x = std::move(y);
    y = std::move(temp);