問題描述
STL中的swap函數是如何實現的?是不是就這么簡單:
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;
}
在其他帖子中,他們談到專門為您自己的班級使用此功能.為什么我需要這樣做?為什么我不能使用 std::swap
函數?
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?
推薦答案
std::swap
是如何實現的?
是的,問題中提出的實現是經典的 C++03 實現.
How is std::swap
implemented?
Yes, the implementation presented in the question is the classic C++03 one.
std::swap
的更現代 (C++11) 實現如下所示:
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);
}
這是在資源管理方面對經典 C++03 實現的改進,因為它可以防止不需要的副本等.它,C++11 std::swap
,要求 T
類型為 MoveConstructible 和 MoveAssignable,從而允許實施和改進.
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.
swap
的自定義實現,對于特定類型,當您的實現比標準版本更有效或更具體時,通常建議.
A custom implementation of swap
, for a specific type, is usually advised when your implementation is more efficient or specific than the standard version.
這方面的一個經典(C++11 之前)示例是,當您的類管理大量資源時,復制和刪除這些資源的成本很高.相反,您的自定義實現可以簡單地交換實現交換所需的句柄或指針.
A classic (pre-C++11) 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.
隨著 std::move
和可移動類型(并實現您的類型)的出現,大約 C++11 及以后,這里的許多原始基本原理開始消失;但是,如果自定義交換比標準交換更好,請實施它.
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.
如果通用代碼使用 ADL機制.
Generic code will generally be able to use your custom swap
if it uses the ADL mechanism appropriately.
這篇關于標準庫是如何實現 std::swap 的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!