Using/Mixing C in C++ code?

前端 未结 12 1562
南旧
南旧 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条回答
  •  Happy的楠姐
    2020-12-24 03:22

    I'm genuinely surprised by the polarization in the answers and comments thereof.

    In my eyes, the answer is pretty simple:

    When writing a C++ project, use C++, avoid C ( and family) and stick to the Standard Library and STL. Ensure a homogenous C++ interface (it is a C++ project after all!) When using an external project in C, which happens to be written in C, of course you can use it. (see examples below)

    Two prime examples:

    1. Write a C++ program/library that does scientific calculations. I would definitely use GSL (GNU Scientific Library), and it is written in C. There are only a few caveats (like specialized initialize and free functions for specific structs and functions within GSL), that can be absorbed in a std::unique_ptr typedef. There is also the issue of error handling: checking error codes can be abstracted away in an exception mechanism if necessary/wanted, or you can keep the error codes contained within the calculation functions. GSL does have a way of setting up an error handler, I imagine some other C libraries have such a functionality.

    2. Writing a C++ program using the Win32 API, which is horribly C based. I'm talking about light API usage, like reading the files in a directory, checking if a file exists, etc., not heavy GDI+ or other stuff. I like to wrap all the C functions the Win32 API exposes in nice C++ style functions, perhaps with the necessary exceptions and returning a std::string instead of having to pass a char* buffer as argument.

    I understand both examples are quite... shallow... but I feel they express a general enough idea.

提交回复
热议问题