When writing a C++ application, I normally limit myself to C++ specific language features. Mostly this means using STL instead of CRT where ever possible.
To me, STL is just so much more fluid and maintainable than using CRT. Consider the following:
std::string str( "Hello" );
if( str == "Hello" ) { ... }
The C-Runtime equivalent would be:
char const* str = "Hello";
if( strcmp( str, "Hello" ) == 0 ) { ... }
Personally I find the former example much easier to look at. It's just more clear to me what's going on. When I write a first pass of my code, the first thing on my mine is always to write code in the most natural way.
One concern my team has with the former example is the dynamic allocation. If the string is static OR has already been allocated elsewhere, they argue it doesn't make sense to potentially cause fragmentation or have a wasteful allocation here. My argument against this is to write code in the most natural way first, and then go back and change it after getting proof that the code causes a problem.
Another reason I don't like the latter example is that it uses the C Library. Typically I avoid it at all costs simply because it's not C++, it's less readable, and more error prone and is more of a security risk.
So my question is, am I right to avoid it the C Runtime? Should I really care about the extra allocation at this step in coding? It's hard for me to tell if I'm right or wrong in this scenario.
const char(&)[N]
, in all other cases usestd::string
. – Jeffereyconst char * const
, which can be compared with anstd::string
. And I rarely need to compare two constant strings, so I neither have to convert a pointer to char to anstd::string
nor to usestrcmp
. – Krugersdorpstrcmp
. If you need to compare a constant string with a variable string in the form of a pointer to char, I would store the constant string in a static constantstd::string
:static const std::string hello("Hello");
. The constant string will be constructed only once in the application lifetime, which should not incur a boundless overhead. – Krugersdorp