Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::string append is not overloaded on rval ref?

I'm familiar, that the append in std::string returns std::string& and therefore it do not qualify to be moved from, so the result will not be moved.

#include <string>


int main()
{
    std::string s = std::string("A").append("B");
    return s.size();
}

https://godbolt.org/z/M63aWW

#include <string>


int main()
{
    std::string s = std::move(std::string("A").append("B"));
    return s.size();
}

https://godbolt.org/z/jTnsac

There you can see, that the latter example will produce one fewer allocation and therefore in this case it is better to move something that may looks like a temporary. My question is why they (the committee) do not add simple overload on && to make the result of append either std::string&, or std::string&& depending on the context? I mean something similar to std::optional is doing with value. Is there a example that will prove such optimization bogus?

like image 263
koscelansky Avatar asked Dec 07 '22 10:12

koscelansky


1 Answers

As is covered in P1165R1, the rules for allocator propagation for basic_string’s operator+ are complex and a root of inconsistencies over different library implementations.

Make stateful allocator propagation more consistent for operator+(basic_string)

[...] Allocator propagation for basic_string’s operator+ is haphazard, inconsistent, and a source of implementation divergence. Let's make them consistent. [...]

P1165R1 has been accepted for C++20.

The append() member function does not have the same semantics, is not as heavily overloaded and does not suffer from the same ”haphazardness ...” as operator+ (prior to P1165R1). There would be no reason for the former to join the domain of the latter; basic_string is already a monster of a container (which is not the case for your counter-example optional, which is not a container in the standardese sense, even if it has semantics similar to a stl container).

like image 68
dfrib Avatar answered Dec 28 '22 17:12

dfrib