memcpy vs for loop – What’s the proper way to copy an array from a pointer?

Yes, the third option is to use a C++ construct:

std::copy(&nums[0], &nums[10], myGlobalArray);

With any sane compiler, it:

  • should be optimum in the majority of cases (will compile to memcpy() where possible),
  • is type-safe,
  • gracefully copes when you decide to change the data-type to a non-primitive (i.e. it calls copy constructors, etc.),
  • gracefully copes when you decide to change to a container class.

Leave a Comment