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 实现.
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模板网!