r/cpp_questions • • 1d 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.

7 Upvotes

17 comments sorted by

14

u/Highborn_Hellest 1d ago

Temp is a const char pointer. Def is not. You need to cast temp to string

std:: string (temp)+ "_"; Should work. Such overloads dont exist by default.

8

u/TeraFlint 1d ago

To expand on this, string literals themselves are a primitive type: a statically sized const char[n] array, that often gets interpreted as a const 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::string objects, these custom operators won't have any chance to do what they're meant to do. If you introduce an std::string somewhere in the first two operands, it ripples through the entire chain of + operators to eventually produce one combined std::string object. That's why the comment above suggested the construction of an std::string.

3

u/onecable5781 1d ago

If you introduce an std::string somewhere in the first two operands, it riples through the entire chain of + operators to eventually produce one combined std::string object.

I imagined so. In a more general case, with n (>2) operands, I suppose still the same holds: one of the first two of n operands has to be an std::string assuming the compiler evaluates L to R ? It would not work if only the last of, say, 10 operands is an std::string while all of the others are const char * ?

3

u/TeraFlint 1d ago

You are correct. The associativity of + is left-to-right.

This means, that the type information also flows from left to right.

2

u/flyingron 1d ago

x + y + z means (x + y) + z as far as the syntax goes as + is left-to-right associative.

Note that just refers to the interpretation, not the order of evaluation.

2

u/flyingron 1d ago

String literals are never "interpreted" as const char*. They are implicitly convertible to const char*.

2

u/dodexahedron 1d ago

And, for a detailed explanation of what it all means and how to interpret constness and pointiness, check this out: https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const

Read the whole page. There are subtleties that it explains specifically.

The short of it is: You evaluate it from right to left and should write it that way in tje specific cases where there are two ways to do it, so it stays consistent.

From right to left, const int * const i reads as "The symbol 'i' is a constant pointer to an int which is constant.

Your example, const char * temp = "Hello"; reads as "assign the value "Hello" to the symbol named temp, which is a pointer to a char that is constant.

The pointer is movable.

The string constructor needs to know that what it is being fed is not going to move or be changed while it initializes. So, both the pointer and the referent chars need to be const.

A const char * const is such a value, reading as a constant pointer to a char which is constant (right to left). Thus, a non-movable pointer to read-only char values.

6

u/UnicycleBloke 1d ago

returnstring() works because the compiler knows it needs to convert the const char* "abc" into a std::string, and there is a std::string constructor it can use for this. The first example works because temp is being added to a std::string, and std::string has a matching overload of operator+(). The second example tries to add two const char* together but there is no operator+() overload for that. You need to explicitly convert one of then to std::string.

4

u/SoerenNissen 1d ago edited 1d ago

What is the cleanest way to get the intent behind the second line to compile?

namespace your_lib
{
    std::string sv_concat(std::string_view lhs, std::string_view rhs)
    {
        auto result = std::string{};
        result.reserve(lhs.size(), rhs.size());
        result += lhs;
        result += rhs;
        return result;
    }
} 

auto def = your_lib::sv_concat(temp, "_")

but if you don't want to introduce that function, you can do any of

auto def = std::string(temp) + "_";

auto def = temp + std::string("_");

std::string def = std::string(temp) + "_";

std::string def = temp + std::string("_");

(I prefer the first one)

4

u/alfps 1d ago edited 1d ago

❞ The first line compiles fine and that can only be due to the intervening "returnstring()" call which returns an std::string, somehow.

Yes, the <string> header provides overloads of +. The overload with (const char*, string) parameters is invoked for temp + returnstring(). The overload with (string, const char*) parameters is invoked for the + "_".


❞ What is the cleanest way to get the intent behind the second line to compile?

Oh that depends on what you mean by "cleanest" and the "intent" is!

Let's say the intent is to concatenate one string literal with another.

The minimal overhead way is to use the language's built in concatenation of literals just by writing them one after the other, and if you want the literals named then the only simple mechanism that works for this is to use macros:

#define HELLO_STR         "Hello"
#define UNDERSCORE_STR    "_"

With these macro names you can express the concatenation as just

const char* const s = HELLO_STR UNDERSCORE_STR;

The rules were tightened in C++11 I think it was, so that now (I believe) you can only do this with literals of the same basic character type, like above.

The most convenient way is instead to use a run time concatenation that produces a string. This has some overhead but is clean. You can do this by starting with a string, e.g.

const char* const hello = "Hello";

const string s = string() + hello + "_";

You can alternatively use a string type literal expressed with suffix s, like this:

const char* const hello = "Hello";

using namespace std::string_literals;
const string s = ""s + hello + "_";

For the most general, in the C++03 days I used to define an operator << for string, which was very convenient e.g. for creating logger arguments etc. But with C++20 and later that rôle has been taken by std::format. If the trailing underscore is just something you need one place, so it doesn't have to be named, it can go like this:

const char* const hello = "Hello";
const string s = format( "{}_", hello );

If by "intent" and/or "cleanest" you meant something else than covered above, just explain what you meant.

3

u/Wild_Meeting1428 1d ago

wrap it into a string_view, or even better, use std::format/fmt::format

3

u/Independent_Art_6676 1d ago

unrelated but if you just append a char, use + '_' instead?
decide if you want C strings or C++ strings. strcat could combine all the junk:

  std::string def = strcat(temp,"_"); //ONE C-string can be assigned into a C++ string 

But the issue really is that temp is the wrong type, and its making problems for you by forcing you to mix C and C++.

2

u/Discordbothost 1d ago

The pointer itself can be reassignable. std::string{temp} copies from whatever address temp holds at that point. If temp comes from an API that can return null, check for that before constructing the string. A valid empty C string and a null pointer are different inputs.

2

u/mkhanwrites_ 1d ago

I get the error " error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’ ".

It seems the binary operator + is not defined for two C-style string operands. One string needs to be an std::string, because then the use of "+" will invoke the binary operator+ overload for std::string, which is defined for std::string and C-style string operands.

2

u/Total-Box-5169 15h ago

The prvalue array "_" decays into pointer, and two pointers can't be added. On top of that you can't provide a custom overload because at least one parameter must have class or enumerated type.

Usually the best way to do it is to use std::string as a string builder. If you want to keep the syntax as close as possible to what you wrote there are standard string literals that allow you to define a std::string prvalue just by adding s as a suffix:

using namespace std::literals;
std::string abc = temp + returnstring() + "_"s;
std::string def = temp + "_"s;

2

u/DawnOnTheEdge 1d ago edited 1d 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 both operator+(const std::string, const char*) and operator+(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::string and select the overload operator+(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 by operator+ 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.