easuter
easuter

Reputation: 1197

using std::swap instead of assignment with '=' operator

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"?

Upvotes: 8

Views: 1664

Answers (1)

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

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.

Upvotes: 10

Related Questions