直接上代码和运行结果
#include <iostream>
#include <string>
#include <sys/time.h>
using namespace std;
const int run_time = 1000*1000;
void CreateStr(string& str)
{
for(int i = 0; i < 100000; ++i)
str += rand()%26 + 'a';
}
std::string GetStr(string& str)
{
return std::move(str);
}
std::string GetStr2(string& str)
{
return str;
}
int main()
{
string str;
string mov_str;
CreateStr(str);
timeval st, et;
gettimeofday(&st, NULL);
for(int i = 0; i < run_time; ++i)
{
mov_str = std::move(GetStr(str));
str = std::move(mov_str);
}
gettimeofday(&et, NULL);
cout << "use std::move, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
gettimeofday(&st, NULL);
for(int i = 0; i < run_time; ++i)
{
mov_str = GetStr2(str);
str = std::move(mov_str);
}
gettimeofday(&et, NULL);
cout << "return directly in function, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
gettimeofday(&st, NULL);
for(int i = 0; i < run_time; ++i)
{
mov_str = GetStr(str);
str = (mov_str);
}
gettimeofday(&et, NULL);
cout << "use assgin after function, time:" << (et.tv_sec-st.tv_sec)*1000 + (et.tv_usec-st.tv_usec)/1000 << "ms" << endl;
return 0;
}
运行结果:
正确用法:
在函数内使用std::move返回,函数返回时仍用std::move赋值。