C++中的exchange用法

263 阅读1分钟

在C++中,std::exchange是一个实用的函数模板,用于在设置对象的新值时返回对象的旧值。它在C++14标准中引入,并在<utility>头文件中定义。

std::exchange的主要目的是简化某些模式下的编程,例如在交换值、重置对象或实现移动赋值操作时。

其实现如下,

template <typename T, typename U = T>
T exchange(T& obj, U&& new_value);

obj:要交换值的对象。 new_value:将赋给obj的新值,可以是不同类型的值。 返回值:obj赋值前的旧值。

下面是一些使用std::exchange的示例:

示例1:基本用法

#include <iostream>
#include <utility>

using namespace std;

int main() {
    int x = 10;
    int old_x = exchange(x, 20);

    cout << "Old value: " << old_x << endl; //输出old value: 10
    cout << "New value: " << x << endl;     //输出new value: 20

    return 0;
}

示例2:在类中使用

std::exchange在类的成员函数中也很有用,尤其是在实现移动赋值操作时。

#include <iostream>
#include <utility> 

using namespace std;

class MyClass {
public:
    MyClass(int value) : value_(value) {}
    
    MyClass& operator=(MyClass&& other) noexcept {
        if (this != &other) {
            value_ = std::exchange(other.value_, 0);
        }
        return *this;
    }

    int getValue() const { return value_; }

private:
    int value_;
};

int main() {
    MyClass a(10);
    MyClass b(20);

    b = move(a);

    cout << "a's value: " << a.getValue() << endl; // 输出 a's value: 0
    cout << "b's value: " << b.getValue() << endl; // 输出 b's value: 10

    return 0;
}

示例3:交换指针

exchange也可以用于交换指针或其它资源管理类对象。

#include <iostream>
#include <utility> 

using namespace std;

int main() {
    int* ptr = new int(42);
    int* old_ptr = exchange(ptr, nullptr);

    cout << "Old pointer value: " << *old_ptr << endl; // 输出 Old pointer value: 42
    cout << "New pointer value: " << ptr << endl;      // 输出 New pointer value: 0x0

    delete old_ptr; // 记得释放旧的指针资源

    return 0;
}