Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 632
easuter Avatar asked Dec 21 '14 00:12

easuter


People also ask

How to use swap directly instead of using std?

std::swap is a built in function of C++ Standard Template Library (STL) which swaps two variables, vectors or objects. :: is the scope resolution operator in C++. To use swap directly instead of using std, we need to set the namespace std like: Parameters : This function requires two parameters which are mandatory.

How to implement the assignment operator in C++?

To implement the assignment operator, we simply need to swap the contents of *this and the argument, other. When other goes out of scope at the end of the function, it will destroy any resources that were originally associated with the current object.

What is swap in C++ with example?

What is std::swap in C++? std::swap is a built in function of C++ Standard Template Library (STL) which swaps two variables, vectors or objects. :: is the scope resolution operator in C++.

How to swap values between two strings in Python?

If you have two strings and want to swap their values, there are two functions both named swap () that you can use. Both functions swap the value of the two strings. The member function swaps *this and str, the global function swaps str1 and str2. These functions are efficient and should be used instead of assignments to perform a string swap.


1 Answers

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.

like image 101
Dietmar Kühl Avatar answered Sep 21 '22 17:09

Dietmar Kühl