为什么不使用 std::move 一切?

问题描述

我不完全理解这个答案。为什么我们不都将类型与 std::move 一起使用?

示例;

std::map<int,int> try;

void foo(std::map<int,int>& try,int t1,int t2)
{
    try.emplace(std::move(t1),std::move(t2));
}

int main()
{
    int k = 1;
    int v = 5;

    try.emplace(k,v); // emplace copies
    foo(try,k,v); // emplace referance
    return 0;
}

那么不同的 emplace 副本和 emplace 引用是什么?我知道 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