Search code examples
c++c++11move-semantics

C++11: Do move semantics get involved for pass by value?


I've got an API that looks like this:

void WriteDefaultFileOutput(std::wostream &str, std::wstring target)
{
    //Some code that modifies target before printing it and such...
}

I'm wondering if it'd be sensible to enable move semantics by doing this:

void WriteDefaultFileOutput(std::wostream &str, std::wstring&& target)
{
    //As above
}
void WriteDefaultFileOutput(std::wostream &str, std::wstring const& target)
{
    std::wstring tmp(target);
    WriteDefaultFileOutput(str, std::move(tmp));
}

or is this just boilerplate that the compiler should be able to figure out anyway?


Solution

  • "Pass by value" can mean either copy or move; if the argument is an lvalue, the copy constructor is invoked. If the argument is an rvalue, the move constructor is invoked. You don't have to do anything special involving rvalue references to get move semantics with pass by value.

    I dig deeper into this topic in What are move semantics?