3

For my implementation of the std-lib the str() implementation for std::stringstream has a str() && version, making it possible to move the string out of the stream without copying it.

My question is, when returning from a function, do you need to specify std::move(...) or is it assumed automatically and can be left out?

Toy example:

#include <sstream>
#include <iostream>

std::string f() {
    auto ss = std::ostringstream{};

    ss << std::string(10000000, '*');
    
    // return std::move(ss.str()); // Is move() required here?
    // return ss.str() // or does this use the str() && implementation?
    return std::move(ss).str(); // Syntax suggested by ALX23z
}

int main() {
    auto x = f();
    std::cout << x << "\n";
}

Edit: Updated to show that my question does not have to do with SSO.

Edit: The answers marked as duplicates does not answer the question I am asking with member functions, and if you were to use the answers given in the "duplicate" questions you would get worse performance. (it's now reopened)

Lasersköld
  • 2,028
  • 14
  • 20
  • 2
    Not only the move is unnecessary, it will likely slowdown the code. You force move rather than letting RVO do its thing. – ALX23z Dec 07 '22 at 08:00
  • 2
    In C++20 you can potentially speed up the code by applying move on the stringstream itself rather than the output of `str()` – ALX23z Dec 07 '22 at 08:02
  • 1
    The syntax is like this `return std::move(ss).str();` – ALX23z Dec 07 '22 at 08:08
  • 1
    Measure! https://quick-bench.com/q/dHJdg5x_zaWuThl7fP9Vx8I7tWI – Osyotr Dec 07 '22 at 08:16
  • 5
    @Osyotr Note that you use short strings in your benchmark, which implies that SSO will be used (and then there is practically no difference between move and copy). For long strings, the situation is different and the solution proposed by ALX23z is the fastest one: https://quick-bench.com/q/krbYDAjBYje3wgS6SsplAV_XPXk. – Daniel Langr Dec 07 '22 at 08:30
  • @ALX23z no that is not correct, atleast not according to the benchmark suggested in the comments. std::move is required. – Lasersköld Dec 07 '22 at 08:48
  • @Osyotr thanks for preparing the benchmark, It used to short strings though. Here is one with really long strings https://quick-bench.com/q/krbYDAjBYje3wgS6SsplAV_XPXk – Lasersköld Dec 07 '22 at 08:50
  • @DanielLangr Yes exactly. My tests with much longer strings seems to get the same results as your that just long enough to trash SSO – Lasersköld Dec 07 '22 at 08:51
  • @ALX23z thanks for the syntax anyway, I did not know that is how you were suppose to write it. – Lasersköld Dec 07 '22 at 08:53
  • Thanks everybody for the help anyways, it seems like we have a winner. – Lasersköld Dec 07 '22 at 08:54

0 Answers0