2

Consider a function that returns a large string:

std::string build_huge_string(unsigned long size)
{
    std::string result;
    result.reserve(size);

    for (unsigned long i = 0; i < size; ++i)
        result.push_back(i % 256);

    return result;
}

It's used somewhere maybe like this std::string huge_string = build_huge_string(65536); Is there a way to make sure the contents of result are moved into huge_string without 64KB worth of stuff being copied?

Is that how it happens by default? Should build_huge_string return std::string&&? Should return result; be replaced with return std::move(result);?

Arya Pourtabatabaie
  • 705
  • 2
  • 7
  • 22
  • 3
    tl;dr: `return result;` _already_ either implicitly moves the value or directly constructs it in the caller's location. `return std::move(result);` prevents direct construction. Returning a `std::string&&` would be a dangling reference - don't do if you're returning a local variable. – alter_igel Jul 16 '19 at 20:04

0 Answers0