Why does wmemcpy exist when memcpy should suffice?

前端 未结 2 1493
别跟我提以往
别跟我提以往 2021-01-18 19:13

wmemcpy appears to perform the same operations as memcpy but accepts wchar_t* instead of void*. How is its existence just

2条回答
  •  自闭症患者
    2021-01-18 19:34

    I guess it's largely about API symmetry, but also, it allows more easily writing code which can work with both wide character and normal strings (switched over by a preprocessor define or similar).

    Essentially, if you want your code to work with char, you #define your copy function as memcpy. For wchar_t, you define it as wmemcpy instead. Your size argument is just the number of characters (either char or wchar_t); remember that the argument isn't necessarily a fixed size array, so using sizeof isn't always an option.

    The Win32 API for instance makes use of a similar strategy: If you define the UNICODE preprocessor symbol, most functions resolve to their wide-character version (suffixed with W) but otherwise they resolve to the "narrow" character version (suffixed with A); TCHAR is defined as either char or wchar_t accordingly; etc. The upshot is you can write code which works with either wide or regular characters fairly easily.

    Of course, this is in no way necessary; but then, the standard C library isn't necessarily supposed to be absolutely minimal. You could argue that calloc is superfluous since you can always use malloc and then memset, for instance; it still exists, however.

提交回复
热议问题