Search code examples
c++cstlcrt

Avoiding the CRT


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.


Solution

  • I feel like my comment about llvm::StringRef went ignored, so I'll make an answer out of it.

    llvm::StringRef str("Hello");
    

    This essentially sets a pointer, calls strlen, then sets another pointer. No allocation.

    if (str == "Hello") { do_something(); }
    

    Readable, and still no allocation. It also works with std::string.

    std::string str("Hello");
    llvm::StringRef stref(str);
    

    You have to be careful with that though, because if the string is destroyed or re-allocated, the StringRef becomes invalid.

    if (str == stref) { do_something(); }
    

    I have noticed quite substantial performance benefits when using this class in appropriate places. It's a powerful tool, you just need to be careful with it. I find that it is most useful with string literals, since they are guaranteed to last for the lifetime of the program. Another cool feature is that you can get substrings without creating a new string.

    As an aside, there is a proposal to add a class similar to this to the standard library.