mardi 30 mars 2021

Does std::move helps with objects on stack?

I just saw a college doing this optimization today:

enter image description here

i.e., change this:

std::string somestring =  "somestring";
std::map<std::string, int> myglobalmap;

std::string myfunction( const std::string& mystring, int myint )
{
    myglobalmap.insert( std::pair<std::string, int>( mystring, myint ) );
}
myfunction(somestring, 10)

To:

std::string somestring =  "somestring";
std::map<std::string, int> myglobalmap;

std::string myfunction( std::string mystring, int myint )
{
    myglobalmap[ std::move(mystring) ] = myint;
}
myfunction(somestring, 10)

He claimed that passing the value mystring by copy instead of passing it as a constant reference would be faster because the move operation would be only performed with objects on the stack. But I could not see why this would help. I searched about the move operator and I found out it does not move anything, it just makes my expression to return a reference.

Then, if this is true, passing the value by copy would not be slower than passing it by reference and calling std::move or does calling std::move help with objects on the stack in this case? If I understand correctly, std::move should only help with objects on the heap. Then, calling it with something on the stack should not help or it does?

Related questions:

  1. What is std::move(), and when should it be used?
  2. Is it possible to std::move local stack variables?

Aucun commentaire:

Enregistrer un commentaire