Search code examples
c++cmemory-managementmixing

Using/Mixing C in C++ code?


Is using C in C++ bad?

Many people have told me that using C in C++ is bad because it's not as safe, and it requires more memory management. I keep telling them that as long as you know what you're doing, and you delete your "new"s and free your "malloc"s then C isn't a problem.

I'm currently on a forum where an argument over std::string vs. a char* is taking place. Some people are saying that allocating a simple char* memory block is more efficient, and as long as you deallocate it, it's fine. On the other hand we have people saying that std::string is superior because it has no memory management involved but is less efficient.

So the main question here is:

  • Is mixing C/C++ bad? Should you ONLY use 100% C++ when you're coding C++?

Any answers would be appreciated!


Solution

  • I keep telling them that as long as you know what your doing, and you delete your new's and free your malloc's then C isn't a problem.

    This is true; if you are extraordinarily careful and ensure that you manually clean things up, then it isn't a problem. But do you really have the time to do that? Every call to new can throw std::bad_alloc. Do you always catch every exception that can be thrown and manually clean up any resources?

    I'd hazard to guess the answer to that is "no," because it is very tedious to write code like that and it is difficult to be absolutely sure that code written like that is correct, even in the case of rare failures.

    If the answer is "yes," then why are you wasting so much time worrying about resource management? C++ idioms like scope-bound resource management (SBRM; more commonly known as resource acquisition is initialization (RAII)) and libraries like the standard template library are there to help you write correct code more easily. Why do things the hard way when you don't have to?

    Should you ONLY use 100% C++ when your coding C++?

    Yes, though if there is a C library that does something you need, or if you have legacy C code that you want to use, you can certainly use that code; just be sure to be careful. Often the cleanest way to interop with C code is to write a C++ wrapper around it.