Since we are just building a string, there is a constructor std::string that takes two iterators:
template< class InputIt > basic_string( InputIt first, InputIt last, const Allocator& alloc = Allocator() );
which we can provide:
std::string newString(&bytes[startIndex], &bytes[startIndex] + length);
If we do not create a string and instead assign an existing one, you still prefer to use assign() . This function is intended for:
oldString.assign(&bytes[startIndex], &bytes[startIndex] + length);
But if you really insist on memcpy() for some reason, then you need to make sure that the line really has enough data to copy. And then just copy it using &str[0] as the destination address & dagger; :
oldString.resize(length);
& dagger; Pre-C ++ 11 there is technically no guarantee that strings are stored in memory contiguously, although in practice this has been done anyway.
Barry source share