5

I wanted to replace my "memcpy" with "std::copy", but I just can't find the right way for passing the args.

My old memcpy code was

memcpy(&uFeatures.Features[0], &((char*)(m_pData))[iBytePos],iByteCount);

I tried various things with std::copy, but they all did not work.

Could anybody help, please?

5
  • What is the type of uFeatures.Features and m_pData? Also, what is the reason why you want to change to std::copy? What "various things" have you tried? Commented May 11, 2013 at 15:59
  • 2
    Wow -- had to go wash my eyes out after looking at that! Commented May 11, 2013 at 15:59
  • I don't see any reason to not use memcpy if your code look like that. Commented May 11, 2013 at 16:07
  • m_pData is a mapped file Commented May 11, 2013 at 16:07
  • I would like to let the compiler decide what it prefers (memcopy, memmove or anything else), that is why I want to use std::copy Commented May 11, 2013 at 16:08

1 Answer 1

2

from your syntax it seems it will be smething like this. (assuming Features[0] is char*, if not you need to cast (check comments) )

std::copy(&uFeatures.Features[0], &uFeatures.Features[0]+iByteCount, &((char*)(m_pData))[iBytePos])

and as I see in your comments

I would like to let the compiler decide what it prefers (memcopy, memmove or anything else), that is why I want to use std::copy

std::copy will not be translated to memcpy by compiler. they are unrelated. copy will do something like this

while (first != last) {
    *d_first++ = *first++;
}
Sign up to request clarification or add additional context in comments.

15 Comments

Thank you, but it crashes for me.
does m_pData have iBytePos+iByteCount bytes memory allocated on it ?
@NeelBasu: that's almost right, but you're mixing "Feature"s (if that's the type of .Features[0]) with byte counts... pointer arithmetic operates in multiples of the structure size so you must either divide iByteCount by that and cast the final char pointer to a Feature*, or covert the Feature*s in the first two arguments to char*. (I can write them both out explicitly if you need).
Just a note on the last bit of your answer. I have seen multiple compilers (and standard libraries) where std::copy was eventually lowered to a memcpy or similar instructions and it is in fact perfectly legal for pod types at least (under the as-if rule).
std::copy is completely different that memcpy memcpy copies a memory chunk, whereas std::copy forwards iterator and assigns. depending on the iterator it may yield the same result. but both are NOT same, and std::copy is NOT a C++ version of memcpy
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.