std::move()基本用法

std::move 是 C++ 标准库中的一个函数,其主要作用是将一个对象显式地转换为右值引用。通过这种转换,我们可以触发对象的移动语义,避免拷贝操作,提高程序效率

(1) 将左值强制转换为右值引用

通常,一个左值无法绑定到右值引用。使用 std::move 可以将左值显式转换为右值引用,从而触发移动语义

#include <iostream>
#include <utility> // for std::move

int main() {
    std::string str = "Hello, World!";
    std::string new_str = std::move(str); // 触发移动构造函数

    std::cout << "Original string: " << str << "\n"; // str 被置空
    std::cout << "New string: " << new_str << "\n"; // new_str 获得原始资源
}

输出:

Original string: 
New string: Hello, World!
  • std::move(str)str 转换为右值引用,调用 std::string 的移动构造函数
  • 移动构造函数将资源从 str 转移到 new_str,避免了深拷贝
  • 原来的 str 被置为空,资源被“偷走”

(2) 触发移动构造或移动赋值

当一个对象是右值时,标准库中的许多类型(如 std::vectorstd::string)提供了专门的移动构造函数移动赋值运算符std::move 通过将左值转换为右值,能够显式调用这些函数

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> vec;
    std::string str = "Hello";

    vec.push_back(str);          // 使用拷贝构造
    vec.push_back(std::move(str)); // 使用移动构造

    std::cout << "Vector contents: ";
    for (const auto& s : vec) {
        std::cout << s << " ";
    }
    std::cout << "\nOriginal string: " << str << "\n"; // str 被置空
}

输出:

Vector contents: Hello Hello 
Original string:
  • 第一次 push_back 调用拷贝构造函数,将 str 的内容复制到容器中
  • 第二次 push_back 调用移动构造函数,将 str 的资源转移到容器中,并将 str 清空

(3) 用于返回值优化

当函数返回一个临时对象时,std::move 可以避免多余的拷贝,直接转移资源

#include <iostream>
#include <vector>
#include <utility>

std::vector<int> createVector() {
    std::vector<int> temp = {1, 2, 3};
    return std::move(temp); // 直接移动 temp 的资源
}

int main() {
    std::vector<int> vec = createVector();
    for (int x : vec) {
        std::cout << x << " ";
    }
}

输出:

1 2 3
  • 函数内部 temp 是一个局部对象
  • 使用 std::movetemp 转换为右值引用,直接转移其资源,而不是拷贝

results matching ""

    No results matching ""