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"?
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.
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 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++.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With