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

问题描述 投票:0回答:1

我不完全理解为什么我们不总是使用 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?

c++ c++11
1个回答
3
投票

不总是移动物体的原因是,移动物体后,你就不再拥有它了。

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
© www.soinside.com 2019 - 2024. All rights reserved.