r/cpp_questions • u/onecable5781 • 7d ago
OPEN Operator + overloads on std::string
Consider https://godbolt.org/z/oY9r59P5E
#include <string>
const char *temp = "Hello";
std::string returnstring(){
return "abc";
}
int main(){
std::string abc = temp + returnstring() + "_";
std::string def = temp + "_";
}
The second line in main() does not compile with the error of "invalid operands". The first line compiles fine and that can only be due to the intervening "returnstring()" call which returns an std::string, somehow.
What is the cleanest way to get the intent behind the second line to compile? In my application, I cannot change const char * temp into an std::string.
8
Upvotes
View all comments
2
u/DawnOnTheEdge 7d ago edited 3d ago
The language only knows which overload a
operator+member function is supposed to call from the left operand. For this reason, the Standard Library declares bothoperator+(const std::string, const char*)andoperator+(const char*, const std::string)as non-member overloads. It doesn’t change the meaning of adding two built-in pointer types.One way to write what you want is:
std::string def = std::string{temp} + "_";
This will construct a temporary
std::stringand select the overloadoperator+(std::string&&, const char*). This overload appends the right operand to the left operand. It then moves rather than copies the modified source operand to the destination object. A modern compiler that inlines the call might only materialize the prvalues created byoperator+and the constructor when needed. This lets it potentially materialze the result of the concatenation in place at the destination object, and also copy-construct the left operand in place, optimizing away the move.You could also write this out as two lines:
std::string def = temp; def += "_";
This makes explicit that the destination object is being copy-constructed from a C-style string, then appended to in place, with no move, like you would want the compiler to optimize the other versions to.