Home > Mobile >  use std::move twice when an argument is passed by value?
use std::move twice when an argument is passed by value?

Time:08-12

I need some feedback in order to see if I understand C move semantics correctly. Can someone tell me if the following example of using std::move - including the statements made in the comments - is correct? (No elaborate comments required if the answer is simply Yes)

#include <string>
#include <utility>

class MyClass
{
public:
  void Set(std::string str)
  {
     myString = std::move(str); 
  }
private:
  std::string myString;
};

int main()
{
  std::string largeString = "A very long piece of text...";
  
  // In the follwoing case largeString is copied once, because it is passed by value (correct?)
  MyClass myClass;
  myClass.Set(largeString);
  
  // In the following case no copies of largeString are made, because it is moved twice (correct?)
  MyClass myClass2;
  myClass.Set(std::move(largeString)); // largeString can no longer be used in main() after this line
  
  return 0;
}

CodePudding user response:

You understood it correctly.
Also you can make your own class, log all constructors and check it by yourself.

  •  Tags:  
  • c
  • Related