mercredi 23 février 2022

Where to use an rvalue as a function parameter?

I know there are plenty of questions about the argument, but I still don't understand some basic stuff about rvalues.

Supposing I have a function of this kind:

/* 1 */ void func( std::string s ) { /* do something with s */ }

which I use in this way:

int main()
{
  func( "a string" );
}

In a case like that, in which I pass this string to the function func wouldn't be better to always define this kind of function in this way:

/* 2 */ void func( std::string&& s ) { /* do something with s */ }

My question is: wouldn't be always better to use /* 2 */ instead of /* 1 */ in cases like the one of this example? And if not, why and where should I use the one or the other? The fact is that, if I understood well, in /* 2 */ the parameter is moved and will never be used outside of the function scope, right?

Aucun commentaire:

Enregistrer un commentaire