如何在C ++中实现交换 [英] How is swap implemented in c++
问题描述
我刚刚开始学习元编程,我想知道交换的实现. 谁能帮助我并解释元编程中的特征概念吗?谢谢.
I just start learning metaprogramming, I wonder the implementation of swap. Can anyone help me and explain the idea of traits in metaprogramming? thanks.
推荐答案
std::swap
被实现为模板,因此它可以交换任何给定类型的两个变量的值.其原型如下:
std::swap
from <algorithm>
is implemented as a template, so that it can exchange the values of two variables of any given type. Its prototype looks like this:
template <typename T> void swap(T& a, T& b);
典型的实现是将一个值保存在临时变量中,将第二个值复制到第一个变量,然后将临时值放入第二个变量.在C ++中,这涉及复制构造函数和赋值运算符.
The typical implementation is to save one value in a temporary, copy the second value to the first variable, and then to put the temporary value into the second variable. In C++, this involves a copy constructor and assignment operators.
对于大型物体,所有这些构造和复制都可能非常昂贵.如此多的对象(包括大多数(全部)STL容器)都具有重载的实现,该实现通过交换一些指针值来工作.交换指针的速度非常快,并且可以避免任何潜在的故障(例如在复制构造函数中进行内存分配).重载的std::swap
转发到成员函数(通常也称为swap
).成员函数可以访问内部函数,因此可以使用更有效的方法.重载可能看起来像这样(简化):
For large objects, all of that construction and copying can be expensive. So many objects, including most (all?) of the STL containers have an overloaded implementation that works by exchanging a few pointer values. Exchanging pointers is very fast, and it avoids any potential failures (like memory allocation during the copy constructor). The overloaded std::swap
forwards to a member function (often also called swap
). The member function has access to the internals, so it can use a more efficient approach. The overload might look something like this (simplified):
template <typename T> void swap<vector<T> >(vector<T>& a, vector<T>& b) {
a.swap(b);
}
如果要查看实际代码,可以浏览std
头文件以查找编译器和操作系统.
If you want to see the real code, you can browse the std
header files for your compiler and OS.
这篇关于如何在C ++中实现交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!