C++右值引用与移动语义面试精讲:从入门到精通本文深入讲解C++11右值引用、移动语义、完美转发的核心概念,配合大量代码示例和面试真题,助你彻底掌握现代C++的性能优化利器。一、左值与右值1.1 值类别#includeiostream#includestringintmain(){inta=10;// a是左值,10是右值intb=a+5;// a+5是右值(纯右值)intc=std::move(a);// std::move(a)是右值(xvalue)// 左值:有名字,可以取地址// 右值:临时对象,不能取地址std::string s1="hello";// "hello"是右值std::string s2=s1+" world";// s1+"world"是右值std::string s3=std::move(s1);// std::move(s1)是右值return0;}1.2 右值引用的语法#includeiostream#includeutilityintmain(){inta=10;// int ref1 = a; // 左值引用,绑定左值// int ref2 = 20; // 错误!左值引用不能绑定右值intrref1=20;// 右值引用,绑定右值intrref2=std::move(a);// std::move将左值转为右值// 右值引用本身是左值!// int rref3 = rref1; // 错误!rref1是左值intlref=rref1;// 正确!右值引用变量本身是左值std::coutrref1std::endl;// 10return0;}二、移动语义2.1 移动构造函数#includeiostream#includestring#includecstring#includeutilityclassBuffer{char*data;size_t size;public:// 构造函数Buffer(size_t n):data(newchar[n]),size(n){std::cout"construct: "sizestd::endl;}// 析构函数~Buffer