这个成语是什么,什么时候应该使用?它解决了哪些问题?当使用C++ 11时,成语是否会改变?
虽然在许多地方已经提到过,但我们没有任何单一的"它是什么"问题和答案,所以在这里.以下是前面提到的地方的部分列表:
c++ c++-faq copy-constructor assignment-operator copy-and-swap
在什么是复制和交换习语这个例子显示:
friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}
Run Code Online (Sandbox Code Playgroud)
如何using std::swap启用ADL?ADL只需要一个不合格的名称.我看到的唯一好处using std::swap是,因为std::swap是一个函数模板,你可以在call(swap<int, int>(..))中使用模板参数列表.
如果不是这样的话,那是using std::swap为了什么?
给出两个std :: vector v1,v2.
我想知道使用std :: swap(v1,v2)比v1.swap(v2)有什么好处.
关于性能观点,我已经实现了一个简单的测试代码(我不确定它是否相关):
#include <iostream>
#include <vector>
#include <random>
#include <chrono>
#include <algorithm>
#define N 100000
template<typename TimeT = std::chrono::microseconds>
struct Timer
{
template<typename F, typename ...Args>
static typename TimeT::rep exec(F func, Args&&... args)
{
auto start = std::chrono::steady_clock::now();
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast<TimeT>(std::chrono::steady_clock::now() - start);
return duration.count();
}
};
void test_std_swap(std::vector<double>& v1, std::vector<double>& v2)
{
for (int i = 0; i < N; i ++)
{
std::swap(v1,v2);
std::swap(v2,v1);
}
}
void test_swap_vector(std::vector<double>& v1, std::vector<double>& …Run Code Online (Sandbox Code Playgroud)