Search code examples
c++move-semantics

In C++, if a funcion takes in a const std::string& as input, can I always call with std::move() on the string input?


I don't know much about the function, except it takes a const std::string&, and I want to call this function from inside a class, and the string input I'm sending in is returned from an instance function on this class.

Is std::move() usage here always safe and more performant, given what we know?

//In some header file:
void some_func_I_only_know_its_signature(const std::string& string_input);

public MyClass{
   public:
     void myFunc(){
         some_func_I_only_know_its_signature(std::move(getMyString()));
     }

  private:
    std::string getMyString(){
        return myString;
    }

    std::string myString_;

};

Solution

  • std::move actually does absolutely nothing here:

    some_func_I_only_know_its_signature(std::move(getMyString()));
    

    The return value of getMyString is already an rvlaue. The thing is std::move actually doesn't move anything. This is a common misconception. All it does is cast an lvalue to an rvalue. If the value is an rvalue and has a move constructor (sdt::string does) it will get moved. But in this case, since the function does not expect an rvalue reference either way you are just going to pass a reference to the return value of getMyString() So you can just:

    some_func_I_only_know_its_signature(getMyString());
    

    That being said the most performant ways is to just:

    some_func_I_only_know_its_signature(myString_);
    

    The function expects a const& which means it only wants read access. Your getMyString() function creates a copy of myString_ and returns it. You don't have to create a copy here, you can just pass a reference to your string directly. get/set functions are usually used for controlled public access to a private field from outside the class.