问题描述
在STL中如何实现交换功能?是这么简单:
模板< typename T& void swap(T& t1,T& t2){
T tmp(t1);
t1 = t2;
t2 = tmp;
}
在其他帖子中,他们谈到专门为您自己的类专门设置此函数。为什么我需要这样做?为什么我不能使用 std :: swap
函数?
如何实现 std :: swap
是的,问题中的实现是经典的C + +03一个。
std :: swap
的更现代(C ++ 11)实现看起来像这样:
template< typename T> void swap(T& t1,T& t2){
T temp = std :: move(t1); //或T temp(std :: move(t1));
t1 = std :: move(t2);
t2 = std :: move(temp);
}
这是相对于经典C ++ 03实现管理,因为它防止不必要的副本等。它,C ++ 11 ,需要 T
类型为和机制。
How is the swap function implemented in the STL? Is it as simple as this:
template<typename T> void swap(T& t1, T& t2) {
T tmp(t1);
t1=t2;
t2=tmp;
}
In other posts, they talk about specializing this function for your own class. Why would I need to do this? Why can't I use the std::swap
function?
How is std::swap
implemented?
Yes, the implementation presented in the question is the classic C++03 one.
A more modern (C++11) implementation of std::swap
looks like this:
template<typename T> void swap(T& t1, T& t2) {
T temp = std::move(t1); // or T temp(std::move(t1));
t1 = std::move(t2);
t2 = std::move(temp);
}
This is an improvement over the classic C++03 implementation in terms of resource management because it prevents unneeded copies, etc. It, the C++11 std::swap
, requires the type T
to be MoveConstructible and MoveAssignable, thus allowing for the implementation and the improvements.
Why would I need to provide a custom implementation?
A custom implementation of swap
, for a specific type, is usually advised when your implementation is more efficient or specific than the standard version.
A classic example of this is when your class manages a large amount of resources that would be expensive to copy and then delete. Instead, your custom implementation could simply exchange the handles or pointers required to effect the swap.
With the advent of std::move
and movable types (and implemented your type as such), circa C++11 and onwards, a lot of the original rationale here is starting to fall away; but nevertheless, if a custom swap would be better than the standard one, implement it.
Generic code will generally be able to use your custom swap
if it uses the ADL mechanism appropriately.
这篇关于标准库如何实现std :: swap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!