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
Show parent comment
8
u/TeraFlint 7d ago
To expand on this, string literals themselves are a primitive type: a statically sized
const char[n]array, that often gets interpreted as aconst char *pointer to its first element.std::string, on the other hand, is nothing more than a class the standard ships. And that class defined the+operator to be usable if it takes part on the left or right side, and if it's paired with a compatible type (one of which is one of these primitive string literals).If you (OP) use
+between two non-std::stringobjects, these custom operators won't have any chance to do what they're meant to do. If you introduce anstd::stringsomewhere in the first two operands, it ripples through the entire chain of+operators to eventually produce one combinedstd::stringobject. That's why the comment above suggested the construction of anstd::string.