CILGINIMAM
CILGINIMAM

Reputation: 113

Why not using std::move everything?

I don't understand fully why we don't always use std::move?

Example;

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;
}

So what is the difference between emplacing copies and emplacing references? I know std::move is more efficient than use copies. (If I'm wrong, sorry. I'm a beginner) So what should I use? Using copies or std::move?

Upvotes: 3

Views: 132

Answers (1)

Jeffrey
Jeffrey

Reputation: 11400

The reason for not always moving an object is that after moving an object, it doesn't necessarily still hold its content anymore.

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 might be gone and you have a valid but different object

Upvotes: 3

Related Questions