Search code examples
c++rvonrvo

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


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);

Solution

  • 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.