欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ 右值引用与移动语义深度解析

时间:2026年08月12日 04:46:50 浏览:0

左值与右值



  • 左值:有地址的变量,可出现在赋值左边。

  • 右值:临时对象,如 10func() 返回值。


int a = 5;  // a 是左值,5 是右值

移动语义


移动语义避免了不必要的拷贝,极大提升性能。


class MyString {
char* data;
public:
// 移动构造函数
MyString(MyString&& other) noexcept : data(other.data) {
other.data = nullptr; // 源对象置空
}

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

// std::move 强制转换为右值
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = std::move(v1); // 移动,v1 变为空

完美转发


std::forward 保留参数的左右值属性。


template<typename T>
void wrapper(T&& arg) {
// 按原始类型转发
func(std::forward<T>(arg));
}

移动语义是现代 C++ 高性能编程的基石。