前置知识: C++

右值引用与移动语义

00:00
1 min Advanced 2026/6/14

右值引用、移动构造与完美转发

1. 左值与右值

int a = 42;    // a 是左值
int&& r = 42;  // 42 是右值,r 是右值引用

// 左值引用:只能绑定左值
int& lref = a;

// 右值引用:只能绑定右值
int&& rref = 42;

// 常量左值引用:可以绑定右值
const int& cref = 42;

2. 移动语义

class String {
  char* data_;
  size_t size_;
public:
  // 移动构造
  String(String&& other) noexcept
    : data_(other.data_), size_(other.size_) {
    other.data_ = nullptr;
    other.size_ = 0;
  }

  // 移动赋值
  String& operator=(String&& other) noexcept {
    if (this != &other) {
      delete[] data_;
      data_ = other.data_;
      size_ = other.size_;
      other.data_ = nullptr;
      other.size_ = 0;
    }
    return *this;
  }
};

3. std::move

std::string a = "hello";
std::string b = std::move(a); // a 变为有效但未定义状态

4. 完美转发

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式