承接上节:右值引用在传参中的提效
查阅 STL 文档可知,C++11 之后容器的 push 和 insert 系列接口增加了右值引用版本。当实参是左值时,容器内部继续调用拷贝构造进行深拷贝;而当实参是右值时,则直接调用移动构造,将资源所有权转移至容器空间对象中。
这里有一个关键点:如果我们要模拟实现 list 并支持右值引用参数版本的 push_back 和 insert,需要注意右值在层层传递时的属性变化。必须使用 move 保持其右值属性,才能正确触发移动构造。
#include <iostream>
#include <string>
#include <list>
using namespace std;
// 假设 bit::string 为自定义字符串类,具有移动构造
namespace bit {
class string {
public:
string(const char* str) { cout << "string(char* str)" << endl; }
string(const string& s) { cout << "string(const string& s) -- 拷贝构造" << endl; }
string(string&& s) { cout << "string(string&& s) -- 移动构造" << endl; }
~string() { cout << "~string() -- 析构" << endl; }
};
}
int main() {
list<bit::string> lt;
bit::string s1("111111111111111111111");
// 左值传入,触发拷贝构造
lt.push_back(s1);
cout << "*************************" << endl;
// 临时对象(右值),触发移动构造
lt.push_back(bit::string("22222222222222222222222222222"));
cout << << endl;
lt.();
cout << << endl;
lt.((s1));
cout << << endl;
;
}


