C++ 我可以在“字节数”设置为零的情况下调用 memcpy() 和 memmove() 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3751797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I call memcpy() and memmove() with "number of bytes" set to zero?
提问by sharptooth
Do I need to treat cases when I actully have nothing to move/copy with memmove()
/memcpy()
as edge cases
我是否需要治疗的情况下,当我actully什么都没有移动/复制用memmove()
/memcpy()
作为边缘情况
int numberOfBytes = ...
if( numberOfBytes != 0 ) {
memmove( dest, source, numberOfBytes );
}
or should I just call the function without checking
或者我应该只调用函数而不检查
int numberOfBytes = ...
memmove( dest, source, numberOfBytes );
Is the check in the former snippet necessary?
是否需要检查前一个片段?
回答by Mike Seymour
From the C99 standard (7.21.1/2):
来自 C99 标准 (7.21.1/2):
Where an argument declared as
size_t n
specifies the length of the array for a function,n
can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4. On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, and a function that copies characters copies zero characters.
如果参数声明为
size_t n
指定函数数组的长度,则n
在调用该函数时可以具有零值。除非在本小节中对特定函数的描述中另有明确说明,否则此类调用的指针参数仍应具有有效值,如 7.1.4 中所述。在这样的调用中,定位字符的函数没有找到,比较两个字符序列的函数返回零,复制字符的函数复制零个字符。
So the answer is no; the check is not necessary (or yes; you can pass zero).
所以答案是否定的;不需要检查(或者是;您可以通过零)。
回答by Matteo Italia
As said by @You, the standard specifies that the memcpy and memmove should handle this case without problem; since they are usually implemented somehow like
正如@You 所说,标准规定 memcpy 和 memmove 应该毫无问题地处理这种情况;因为它们通常以某种方式实现
void *memcpy(void *_dst, const void *_src, size_t len)
{
unsigned char *dst = _dst;
const unsigned char *src = _src;
while(len-- > 0)
*dst++ = *src++;
return _dst;
}
you should not even have any performance penality other than the function call; if the compiler supports intrinsics/inlining for such functions, the additional check may even make the code a micro-little-bit slower, since the check is already done at the while.
除了函数调用之外,您甚至不应该有任何性能损失;如果编译器支持此类函数的内在/内联,则额外的检查甚至可能会使代码稍微慢一点,因为检查已经在 while 中完成了。