编译器在用少量字节调用时会优化memcpy调用吗?
对于此示例的代码:
#define _CRT_SECURE_NO_WARNINGS // To allow usage of scanf in vc++2015
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
// printf and scanf to prevent code elimination
char bytes[ 4 ];
scanf("%s", bytes);
char buffer[ 4 ];
memcpy(buffer, bytes, 4);
printf("%s", buffer);
return 0;
}
的Visual C++ 2015生成此组件的输出(发布版本,X64):
; memcpy was replaced by a simple register move
mov eax, DWORD PTR bytes$[rsp]
lea rdx, QWORD PTR buffer$[rsp] ; setting arguments
lea rcx, OFFSET FLAT:[email protected][email protected][email protected] ; for printf call
; at this point copied array was actually stored in memory
mov DWORD PTR buffer$[rsp], eax
call printf
所以,是现代编译器甚至不会调用该过程。
是的,只需使用'memcpy()',它是大多数现代(<10年)编译器的内在功能。 –