相关疑难解决方法(0)

什么是复制和交换习语?

这个成语是什么,什么时候应该使用?它解决了哪些问题?当使用C++ 11时,成语是否会改变?

虽然在许多地方已经提到过,但我们没有任何单一的"它是什么"问题和答案,所以在这里.以下是前面提到的地方的部分列表:

c++ c++-faq copy-constructor assignment-operator copy-and-swap

1907
推荐指数
5
解决办法
34万
查看次数

"使用std :: swap"如何启用ADL?

什么是复制和交换习语这个例子显示:

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为了什么?

c++ argument-dependent-lookup c++11

14
推荐指数
2
解决办法
3076
查看次数

在vector或vector :: swap之间使用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)

c++ swap vector c++11

5
推荐指数
2
解决办法
4988
查看次数

std::ranges::swap() 和 std::swap() 有什么区别?

在C++20中,有两个swap函数模板:std::ranges::swap(T&&, U&&)std::swap(T&, T&)

我只是好奇:

他们两个有什么区别?

c++ standards stl c++20 std-ranges

4
推荐指数
1
解决办法
650
查看次数