This is my C++ code:
inline static void swap(std::string& a1, std::string& a2) {
std::string temp( std::move(a1));
a1 = std::move( a2 );
a2 = std::move( temp );
}
std
std::swap
According to the standard ยง21.3.2.8/p1 swap [string.special] (Emphasis Mine):
template<class charT, class traits, class Allocator> void swap(basic_string<charT, traits, Allocator>& lhs, basic_string<charT, traits, Allocator>& rhs) noexcept(noexcept(lhs.swap(rhs)));
1 Effects: Equivalent to:
lhs.swap(rhs);
Consequently, std::swap
specializes/has an overload for std::string
and is equivalent as calling the member function std::basic_string::swap
.
A possible implementation would be:
template<class Elem, class Traits, class Alloc>
inline
void
swap(std::basic_string<Elem, Traits, Alloc>& left,
std::basic_string<Elem, Traits, Alloc>& right) noexcept(noexcept(left.swap(right))) {
left.swap(right);
}
As for why your implementation is slower, my guess is that even if you move the one string to the another, the destructor for the temporary string will still be called. Something that is not the case in the STL compatible implementation above.