Compiler Optimization with return (std::stringstream ss).str()

672 Views Asked by At

The following function accepts a string as an argument, and returns another, after some processing.

  1. Is it fair enough to assume that the compiler will perform move optimizations, and I will not end up having the contents of string copied after every invocation? Should this function follow the copy elision [(N)RVO]?

  2. Is this, as a practice, advisable?

std::string foo(std::string const& s)
{ // Perform sanity check on s
  // ...

  std::stringstream ss;
  // do something and store in ss
  // ...

  return ss.str();
}

Because, otherwise, I generally follow the practice of returning strings by reference. So, to say, my function signature would have been:

void foo (std::string const& inValue, std::string& outValue);
2

There are 2 best solutions below

2
On BEST ANSWER

ss.str() will create a temporary string. If you are assigning that string to a a new instance like

std::string bar = foo("something");

The either copy elision or move semantics will kick in.

Now if you have an already created string and you are assigning it to the return of foo then move assignment will kick in

std::string bar;
// do stuff
bar  = foo("something");

I prefer this method as it does not require you to have an object already created where

void foo (std::string const& inValue, std::string& outValue);

Would have you create an empty string just to pass it to the function to get filled. This means you have a construction and a assignment where with the first example you could just have a construction.

0
On

According to this it is more optimized when you return the value:

the Return Value Optimization (RVO), allows the compiler to optimize away the copy by having the caller and the callee use the same chunk of memory for both “copies”.