Why has std::swap
been moved to the <utility>
header for C++11?
N3290 C.2.7 says:
17.6.3.2
Effect on original feature: Function swap moved to a different header
Rationale: Remove dependency on
<algorithm>
for swap.Effect on original feature: Valid C++ 2003 code that has been compiled expecting swap to be in
<algorithm>
may have to instead include<utility>
.
I can't understand the part in bold. What kind of dependency is being talked about and why?
It is not atomic. Atomic operations are not cheap and 99% of the time you do not need the atomicity. There are (IIRC) some other means to get atomic operations but std::swap() is not one of them.
The std::swap() function is a built-in function in the C++ STL. The swap(T& a, T& b) function calls by reference and the C++ overloads swap( ) function based on the data types of the variables passes, if the variables pass of different data types the swap( ) function throw error or exception.
utility is a header file in the C++ Standard Library. This file has two key components: rel_ops , a namespace containing set of templates which define default behavior for the relational operators != , > , <= , and >= between objects of the same type, based on user-defined operators == and < .
It is a header file that contains utilities in unrelated domains. Pairs: These are the objects which can hold two different types of values. Generic Relational Approach: It is used for the relational operators != , >, = under a specific namespace: rel_ops.
The committee wanted to allow you to use swap()
without introducing a compile-time dependency on the large and more complex <algorithm>
header file. Because swap()
is so widely used, it makes sense to let you pull in its definition with as little additional baggage as possible; this will generally lead to faster compile times for files that don't otherwise need <algorithm>
. Its new home allows it to be used without introducing unneeded overhead.
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