“const void*”是什么意思?意思是memmove?
memmove/memcpy/strcpy 原型中的第二个参数类似: 例如:
void *memmove(void *dest, const void *src, size_t n); //const void*
char *strcpy(char *dest, const char *src); //const char*
但显然,如果 dest 和 src 重叠,那么 src 的内容将被更改,违反 const void/char *?
The second arg in the prototypes for memmove/memcpy/strcpy are similar:
For example:
void *memmove(void *dest, const void *src, size_t n); //const void*
char *strcpy(char *dest, const char *src); //const char*
But apparently, if dest and src overlap, then src's content will be altered, violating the const void/char *?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
const void*
表示引用对象不会通过该指针进行修改。如果还有其他指向同一对象的非常量指针(也称为“别名”),那么当然仍然可以通过这些指针对其进行修改。在您描述的场景中,另一个指针是
dest
。顺便说一句,在 strcpy 的情况下,如果区域重叠,则行为是未定义的,在 C99 中,签名为 char *strcpy(char * limit s1, const char * limit s2); 。但对于 memmove 来说,别名是可以的。通过给它重叠的区域,你就给了它修改
dest
区域的“权限”,它就会这样做。const void*
means that the referand will not be modified through that pointer.If there are other, non-const pointers to the same object (also known as "aliasing"), then of course it can still be modified through those. In the scenario you describe, that other pointer is
dest
.By the way, in the case of
strcpy
, behavior is undefined if the regions overlap, and in C99 the signature ischar *strcpy(char * restrict s1, const char * restrict s2);
. But for memmove, aliasing is OK. By giving it overlapping regions you've given it "permission" to modify thedest
region, and it will do that.该参数被标记为 const void * 来指示 memmove 永远不会使用该指针修改 src 指向的内存。如果发生重叠,则使用
dest
指针修改内存,而不是src
指针,因此不会违反保证。The argument is marked
const void *
to indicatememmove
will never modify the memory pointed to bysrc
using that pointer. If overlap occurs the memory is modified using thedest
pointer, not thesrc
pointer, so the guarantee is not violated.这意味着
memmove
保证它不会直接修改src
指向的内存。当然,如果两个块重叠
memmove
将会改变所谓的“const”内存。const
是附加到名称的 ca 契约。没有办法使实际内存只读。It means
memmove
guarantees it won't directly modify the memory pointed bysrc
.Of course if the two blocks overlap
memmove
will change the so-called "const" memory.const
is ca contract attached to a name. There's no way to make the actual memory read-only.如上所述,memove 不会通过“src”指针修改内存内容,而是通过“dest”指针修改内存内容。
const 指的是指针的使用方式,它不添加任何内存保护。
如果两个指针都指向内存的重叠区域,那么任何事情都可能发生,因为没有定义副本是否从“src”开始并递增或从“src + n”开始并递减。
As above memove will not modify the contents of memory through the "src" pointer but will through the "dest" pointer.
The const refers to how the pointers are used, it does not add any memory protection.
If both pointers to point to an overlapping region of memory then anything could happen as it's not defined if the copy will start from the "src" and increment or start from "src + n" and decrement.