8

I was going over some C++ source code from a library related to a pet-project I'm working on and encountered something I don't understand. In a place where I expected a pointer dereference followed by assignment, the library authors use std::swap() near the end of the function to write the result:

std::swap(*out, result);

I expected to see something like this:

*out = result;

Note that result is a typedef of size_t and out is a pointer to that same type.

When it comes to "systems programming", my background is in C and C# but not much at all in C++. Is there any particular reason for this type of "assignment"?

jww
  • 97,681
  • 90
  • 411
  • 885
easuter
  • 1,167
  • 14
  • 20
  • 1
    If the value `result` is *not* used after the swap, the `std::move` may be a better choice. Also see [What exactly is a R-Value in C++?](http://stackoverflow.com/q/9406121/608639). – jww Dec 21 '14 at 01:15
  • @jww, `result` isn't used after the call to `std::swap`. – easuter Dec 21 '14 at 11:10

1 Answers1

10

When the value types are more interesting, say, a std::vector<T>, for example, it may make more sense to std::swap() a temporarily constructed object into place rather than assigning it: given that the temporary result is about to go away, avoiding an assignment and just changing pointers makes some sense. I don't see any reason to do something like that with fundamental types like std::size_t, though.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • 3
    **+1** for the concise answer. Or, in C++11, can use move semantics to get rid of the assignment. I'd point out that the `swap` construction is frequently seen in the copy-and-swap idiom http://stackoverflow.com/q/3279543/3093378, when you want to make sure you're not leaving objects in undefined states whenever you copy them due to exception throwing. – vsoftco Dec 21 '14 at 01:14