For this code:
std::array<unsigned char, 6> myArray = {123, 123, 112, 0, 15};
std::chrono::milliseconds dest{0};
memcpy(&dest, &myArray, 5);
Gcc gives the following error:
warning: 'void* memcpy(void*, const void*, size_t)' copying an object of type 'std::chrono::milliseconds'
{aka 'struct std::chrono::duration<long int, std::ratio<1, 1000> >'}
with 'private' member 'std::chrono::duration<long int, std::ratio<1, 1000> >::__r'
from an array of 'struct std::array<unsigned char, 6>';
use assignment or copy-initialization instead [-Wclass-memaccess]
What would be the best way to handle this when I need to copy only 5 bytes from array and not the whole array?
Here is my full code:
std::array<uint8_t, 6> myArray = {0};
uint32_t time = 500000000;
memcpy(&myArray, &time, 4);
std::chrono::milliseconds ret{0};
memcpy(&ret, &myArray, 4);
So im trying to get same value in ret
as the one in time
The safer way to implement this that doesn't rely on knowing the internal layout of std::chrono::duration
would be to copy to an integer then pass the integer to the duration:
std::array<unsigned char, 6> myArray = {123, 123, 112, 0, 15};
int64_t milliseconds = 0;
memcpy(&milliseconds, &myArray, 5);
std::chrono::milliseconds dest{milliseconds};