1

Here is the specialization version for char* :

inline char* uninitialized_copy(const char* first, const char* last, char* result)
{
  memmove(result, first, last-first);
  return result + (last - first);
}

It is said that memmove is the most efficient way for char* and w_char* to implement this method. But Why can't int* and other basic type be implemented in this way?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
venus.w
  • 2,171
  • 7
  • 28
  • 42

2 Answers2

1

When the standard was designed, it was believed that some specializations like this could be used to improve performance. As it turned out, the compilers got better and generate the same code anyway from the base template.

Many current compilers even have the memmove function built in and generate improved inline versions when they can take advantage of known alignment or when the size of the objects happen to be an even multiple of the register size.

Here is my favorite exemple of when the compiler realizes that an 8 byte string can be copied using a single register move.

Community
  • 1
  • 1
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
0

The C++ standard actually does not say that there should be specializations of uninitialized_copy for these types; it just mandates that there should be a template function called uninitialized_copy that should work on iterator ranges. However, the C++ standard does permit compiler and library authors to implement their own specializations of this function if they choose to do so.

There are many good reasons to specialize uninitialized_copy to work on individual characters. In some cases, compilers provide intrinsics for memmove and memcpy that are much faster than the code they would normally output due to normal optimizations. As a result, specializing this code for the char and wchar_t types would make sense, as these intrinsics would outperform a standard loop.

It is hard for me to say exactly why the library authors didn't specialize for other types. My guess is that they tested this out and didn't find much of a performance difference. Since anything the library authors do above providing the standard template version of uninitialized_copy is just going above and beyond what the spec requires, it could simply be because they were busy and needed to work on something else. You'd have to contact them directly to get a more definitive answer.

In short - the library authors aren't required to provide any specializations at all, and it's nice that they chose to put in this specialization. Without contacting them, it's hard to say definitively why they didn't choose to do this for other types.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065