Tre*_*key 0 c string const const-correctness ctype
查看C标准库中的大多数函数,似乎缺少const,其中指定so,通常是首选.
例如:
ctype.h/c
extern int isupper(int __c) __ATTR_CONST__;
extern int islower(int __c) __ATTR_CONST__;
extern int isdigit(int __c) __ATTR_CONST__;
Run Code Online (Sandbox Code Playgroud)
为什么不是这些:
extern int isupper(const int __c) __ATTR_CONST__;
extern int islower(const int __c) __ATTR_CONST__;
extern int isdigit(const int __c) __ATTR_CONST__;
Run Code Online (Sandbox Code Playgroud)
他们毕竟只观察参数:
int isupper(int c) {
return _pctype[c] & _UPPER;
}
int islower(int c) {
return _pctype[c] & _LOWER;
}
int isdigit(int c) {
return _pctype[c] & _DIGIT;
}
Run Code Online (Sandbox Code Playgroud)
或者让我们在string.c中使用一个函数:
void *memcpy(void *dest, const void *src, size_t count)
{
char *tmp = dest;
const char *s = src;
while (count--)
*tmp++ = *s++;
return dest;
}
Run Code Online (Sandbox Code Playgroud)
为什么不:
void *memcpy(void *const dest, const void *const src, size_t count);
Run Code Online (Sandbox Code Playgroud)
在这些地方被排除在外是有原因吗?
以我所展示的方式包含const是不对的?
我认为由于历史原因,这些功能一直保持这种状态,
但我想如果我错过了一些东西,我应该问一下.
那些是 const-correct签名.
你几乎不会在传值参数之前写const.该函数有自己的副本,所以没有危险.
void *memcpy(void *dest, const void *src, size_t count)
Run Code Online (Sandbox Code Playgroud)
是const也是正确的.只有第二个指针才会改变它所指向的内容.另一方面,目标指针是关于改变它指向的内容.
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |