我的博客

C++ std::move

目录

今天读一份源码看到了如下函数

1
2
3
4
Json Logic::afterRecv(Json message) {
message["recvTime"] = GlobalUtil::curTime();
return std::move(message);
}

却不知道 std::move 是什么。查了一下资料

发现他是一个模板函数,来自于头文件 utility。

例子(来自 http://www.cplusplus.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// move example
#include <utility> // std::move
#include <iostream> // std::cout
#include <vector> // std::vector
#include <string> // std::string

int main () {
std::string foo = "foo-string";
std::string bar = "bar-string";
std::vector<std::string> myvector;

myvector.push_back (foo); // copies
myvector.push_back (std::move(bar)); // moves

std::cout << "myvector contains:";
for (std::string& x:myvector) std::cout << ' ' << x;
std::cout << '\n';

return 0;
}

第一次调用 push_back 把 foo 的值拷进 vector 里了,foo 的值没有变化。第二次调用,变量 bar 失去了它的值。

第一次调用 push_back 调用了拷贝构造函数,第二次调用了移动构造函数。

这篇文章有更详细的讲解,还提到了一个工具 valgrind。

评论无需登录,可以匿名,欢迎评论!