Difference between string.h and cstring?

前端 未结 7 1319
耶瑟儿~
耶瑟儿~ 2020-12-03 03:13

What is the difference between string.h and cstring?

Which one should be used for C and which one for C++ (if at all)?

7条回答
  •  难免孤独
    2020-12-03 03:47

    The C++ version of the header actually has some differences from the C version. In C some types are implemented as typedefs, but for C++ that prevents things like template specialization from working on those types*, so C++ makes some C typedefs into real types. This means that the C++ version of C headers that contain those typedefs must omit them.

    C++ also allows overloading and so the C++ version of specifies some overloads to C functions to allow a function to return a pointer to non-const data if the input argument is a pointer to non-const data, whereas the C function takes and returns only pointers to const.

    Also I think, but can't find the bit in the standard to verify this right now, that the C++ versions of headers have to put their names in the std namespace and only put them in the global namespace as an optional extension.

    * For example the following code:

    typedef int Foo;
    template struct Bar {};
    template<> struct Bar {};
    template<> struct Bar {};
    

    results in the following error:

    main.cpp:7:19: error: redefinition of 'Bar'
    template<> struct Bar {};
                      ^~~~~~~~
    main.cpp:5:19: note: previous definition is here
    template<> struct Bar {};
                      ^
    1 error generated.
    

    In C wchar_t is a typedef, so this would prevent one from having a specialization that applies to wchar_t but not to whatever underlying type is used for wchar_t. The fact that MSVC 2010 implements char32_t and char16_t as typedefs prevents them from being able to offer the std::codecvt specializations for those types.

提交回复
热议问题