So how do you quickly concatenate strings? -- Aleksandr Orefkov

So how do you quickly concatenate strings?

By Aleksandr Orefkov

From the article:

All practicing programmers have to concatenate strings. Precisely concatenate, we don’t have some JavaScript or PHP, in C++ we have this fancy word for it. Programmers in other languages ​​simply “add” strings together without much thought, without even thinking about this operation. After all, what could be simpler than

return "The answer is " + str_answer + ", count is " + count;

But while it’s forgivable for script kiddies not to think about the meaning behind such a simple notation, it’s unacceptable for an experienced developer to approach such an important issue so irresponsibly. An experienced developer, imagining such C++ code, immediately sees the terrifying abyss of problems that such an approach can create.

What type is str_answer? What type is count? “The answer is “ and “, count is “ - are literals that add to std::string as a const char*. So, strlen will be called. I wonder if the compiler will be able to optimize and calculate their length at compile time? Oh well, it seems like constexpr is in the addition, let’s hope so.
This is the first level of problems for now. And let’s say we successfully solved them, creating the following code:

std::string make_answer(std::string_view str_answer, int count) {
    return "The answer is " + std::string{str_answer}
        + ", count is " + std::to_string(count);
}

It sounds like “Hurray!”, but it’s somehow not loud enough…

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.