Remix.run Logo
MrLeap 7 months ago

C++ was the first programming language I ever learned, but I've only written a few hundred lines of it over the last 2 decades. Never professionally.

Can you elaborate on the dangers of doing this incorrectly? What kinds of dangers are there in making a string literal available to a header file.

ranger_danger 7 months ago | parent [-]

Not OP but I think it depends on your definition of 'string'. For example there are some very grumpy devs who believe that C has no strings, and that "const char*" cannot ever be considered a string, and that anyone else who claims so is wrong.

tialaramex 7 months ago | parent [-]

This is made more confusing by C++ basically insisting that your "basic" built-in string type has to have the small string optimisation. The guts of std::string in any of the three popular stdlib implementations are... pretty complicated. In contrast Rust's String is literally just Vec<u8> [a growable array of bytes] plus a promise that these bytes are always a UTF-8 encoded string.

And by C++ taking a long time to get the natural string slice type, which it calls `std::string_view`. This type is what you almost always want in APIs that aren't responsible for growing and changing strings - for the names of things, labels, parsing and so on. Because this type was not in C++ 98 or C++ 11 or even C++ 14 people would use `std::string` instead even though they did not need to modify, let alone grow, the text or, since they don't want the overhead of `std::string`, they would use `char *`

It was correct for C++ to seek to do better than C here, but while what they delivered was a lot more powerful it's not clearly better and I think has contributed to widespread misunderstanding.

saagarjha 7 months ago | parent [-]

C++ doesn't require any of this. Everyone implements it this way because it is cheap and improves performance. And people don't take (const) char * they take const std::string &.