#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
{
std::string str = "Hello";
std::vector<std::string> v;
//调用常规的拷贝构造函数,新建字符数组,拷贝数据
v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
//调用移动构造函数,掏空str,掏空后,最好不要使用str
v.push_back(std::move(str));
std::cout << "After move, str is \"" << str << "\"\n";
std::cout << "The contents of the vector are \"" << v[0]
<< "\", \"" << v[1] << "\"\n";
}
输出:
After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"
std::move(str)将str从左值转为右值引用,然后在push_back的时候,根据类型是右值引用,因此会调用string类的移动构造函数,从而大大提升了效率。
代码地址:blog.csdn.net/p942005405/…
class MyString {
public:
MyString(){
std::cout << "default constructor." << std::endl;
}
MyString(const MyString& rhs) {
std::cout << "copy constructor." << std::endl;
}
MyString& operator=(const MyString& rhs) {
std::cout << "assignment constructor." << std::endl;
}
MyString(MyString&& rhs) {
std::cout << "move constructor" << std::endl;
}
private:
char* data_;
int32_t data_size_;
};
MyString func_mystr()
{
MyString x;
//return x;
return std::move(x);
}
int main()
{
// 0. std::move
MyString a;
MyString c;
MyString d = c; // copy constructor
MyString b = std::move(a); // move constructor
std::cout << "###############" << std::endl;
MyString e = func_mystr();
}
输出:
default constructor.
default constructor.
copy constructor.
move constructor
###############
default constructor.
move constructor
而如果func_mystr()里写成return x,则输出为:
###############
default constructor.
具体解释参考:thbecker.net/articles/rv…
简单说就是编译器会自动优化,用了std::move,反而使得编译器不好优化了.