Using/Mixing C in C++ code?

前端 未结 12 1559
南旧
南旧 2020-12-24 03:03

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 tha

12条回答
  •  -上瘾入骨i
    2020-12-24 03:21

    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.

提交回复
热议问题