我不完全理解为什么我们不总是使用 std::move?
示例;
std::map<int, int> test;
void foo(std::map<int, int>& test, int t1, int t2)
{
test.emplace(std::move(t1), std::move(t2));
}
int main()
{
int k = 1;
int v = 5;
test.emplace(k , v); // emplace copies
foo(test, k, v); // emplace references
return 0;
}
那么放置副本和放置参考文献有什么区别?我知道 std::move 比使用副本更有效。 (如果我错了,抱歉。我是初学者)那么我应该使用什么?使用副本还是 std::move?
不总是移动物体的原因是,移动物体后,你就不再拥有它了。
void f()
{
Object o;
o.stuff();
SomeFunctionTakingAReference(o);
o.stuff(); // your o object is still usable
SomeFunctionTakingAReference(std::move(o));
// Here your o object is not valid anymore. It's gone and you have a valid but different object