C++ How to code string constants

Beginner or not, average (or not) C++ developer might think this is a non-issue. Nothing to talk about.

I would like to disagree.

I am pretty sure this “no-brainer” pulls a lot of legacy code and legacy thinking into the realm of your C++ code. Just a few short examples:

And so on and on. And yes more astute developers have interlaced the above “solutions” with a good and simple “lazy instantiation” idiom:

A variant of the above, with more or much more C++ artefacts around it, is very often considered as “ultimate”  solution to the application wide string constants. And left as a such in the tons of running code worldwide.

So what?

One might ask. Well, the first problem is this very often does not play well with standard C++.  Especially the naked pointer variant. Whenever the single native char pointer is delivered, one has to transform it into the std::string and then use it with standard C++ std:: algorithms, utilities and a such.

Above usage pattern is of course riddled with issues. So it is much better to copy the constant in these kinds of situations. Which is not very efficient.

A bit better solutions are not using C++17 or even 14 or 11, “goodies”. So they usually produce slower and heavier programs. Etc, etc …

By now I am sure you are “getting the picture”. Enough of this essay and let us jump straight into the

Standard solution

We use the standard C++ artefact: string views. The standard string interface to the non-changeable native charr array. And equally importantly with value semantics.  Meaning moving/copying is implemented for us.

To involve this kind of constant into her modern C++ code, one does not need to transform it into anything. Just use it. It will be very resilient and safe to use too.

Very quick test

Yes, this solution is usable at both compile time and runtime. Regardless of the fact it is not based on a fundamental type. (At least on my machine using CL Version 19.15.26726.0)

Here are the few “show offs” using the std:: c++ and this kind of a solution for application wide string constants

Solution based on string views, will not enforce costly transformations in the client code and, god forbid, subtle bugs, creeping in with the use of char pointers or native char arrays.

Enjoy the standard C++. It is really not that difficult. Just make sure to leave the legacy behind.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.