Using std :: swap instead of assignment using the '=' operator

I was sorting through some C ++ source code from a library related to the home project I'm working on, and came across something, T understand. In the place where I was expecting the pointer to be dereferenced followed by assignment, the authors of the library 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 the same type.

When it comes to "system programming", my background is in C and C #, but not very much in C ++. Is there any special reason for this type of "appointment"?

+7
c ++ variable-assignment swap
source share
1 answer

When value types are more interesting, for example, std::vector<T> , for example, it may make sense to assign a temporarily constructed object to it instead: given that the temporary result is just off, avoiding the task and just changing the pointers , has the meaning. I see no reason to do something similar with such fundamental types as std::size_t .

+9
source share

All Articles