gpt4 book ai didi

c++ - string.h 和 cstring 之间的区别?

转载 作者:IT老高 更新时间:2023-10-28 22:17:19 33 4
gpt4 key购买 nike

string.hcstring 有什么区别?

哪个应该用于 C,哪个用于 C++(如果有的话)?

最佳答案

在 C++ 中,您应该包含 cstring作为 c 中的标题,您应该包含 string.h作为标题。

在 C++ 中

#include <cstring>

在 C 中

#include <string.h>

C++ 标准库中也提供了 C 标准库的特性,作为一般命名约定,它们前面加上 c到 C 标准库中的相应名称。

例如:
string.h变成 cstring
stdio.h变成 cstdio等等……


由于其他答案为这个讨论增加了不同的维度,我觉得有必要引用神圣的标准来清除这一点。

根据 C++11 20.9.14.6 & 7:

Table 55 describes the header <cstring>.
The contents are the same as the Standard C library header , with the change to memchr() specified in 21.7.

21.7 空终止序列实用程序 声明:

The function signature memchr(const void*, int, size_t) shall be replaced by the two declarations:

const void* memchr(const void* s, int c, size_t n);
void* memchr( void* s, int c, size_t n);

both of which shall have the same behavior as the original declaration.

附录 D(规范性)兼容性特性 [depr] 规定:

D.6 C 标准库头文件

1 For compatibility with the C standard library and the C Unicode TR, the C++ standard library provides the 25 C headers, as shown in Table 151.

其中包括:

<assert.h> <float.h> <math.h> <stddef.h> <tgmath.h> <complex.h> <inttypes.h> <setjmp.h> <stdio.h> <time.h> <ctype.h> <iso646.h> <signal.h> <stdint.h> <uchar.h> <errno.h> <limits.h> <stdarg.h> <stdlib.h> <wchar.h> <fenv.h> <locale.h> <stdbool.h> <string.h> <wctype.h>

接下来,

2 Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3).

3 [ Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. The header <stdlib.h> assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespace std. —end example ]

结论:

从以上引用:
我已经纠正了我之前的建议,使用 cstring 似乎没有明显的优势超过 string.h而正如@Alf 建议的那样,由于在使用 cstring 时使用了不合格的函数名,可能会出现一些编译问题。作为标题。所以给定帽子,使用 string.h 没有明显的缺点。或使用 cstring 的优势,如果使用得当,我认为两者都可以在 C++ 中使用。

关于c++ - string.h 和 cstring 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380805/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com