move semantic
move semantic
假设我们有如下的代码
motiv03.cpp
#include <string>
#include <vector>
std::vector<std::string> createAndInsert()
{
std::vector<std::string> coll;
coll.reserve(3);
std::string s = "data";
coll.push_back(s);
coll.push_back(s + s);
coll.push_back(s);
return coll;
}
int main()
{
std::vector<std::string> v;
v = createAndInsert();
return 0;
}
对于不支持移动语义的编译器(C++03),这段代码需要分配10次并且释放6次内存.不必要的内存分配主要是因为:
- 将一个临时变量插入到集合中
- 将一个不再需要的对象插入到集合中
- 为一个临时的集合及其所有元素赋值
我们可以通过传递一个vector作为参数或者使用swap()来避免最后一次的赋值
但是,这看起来非常的繁琐而且无法解决前两个问题.因此,C++11引入了移动语义
#include <string>
#include <vector>
std::vector<std::string> createAndInsert()
{
std::vector<std::string> coll;
coll.reserve(3);
std::string s = "data";
coll.push_back(s);
coll.push_back(s + s);
coll.push_back(std::move(s));
return coll;
}
int main()
{
std::vector<std::string> v;
v = createAndInsert();
return 0;
}