标准库是如何实现 std::swap 的?

How does the standard library implement std::swap?(标准库是如何实现 std::swap 的?)
本文介绍了标准库是如何实现 std::swap 的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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 类型为 MoveConstructibleMoveAssignable,从而允许实施和改进.

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 的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)