Search code examples
c++cconstantsmemcpy

why cant I use const arguments in memcpy?


I have a struct cVector3d and I am memcpy'ing it into a char array like this:

void  insert_into_stream(std::ostream& stream,  cVector3d vector)
{
    int length = sizeof(double)*3;
    char insert_buffer[sizeof(double)*3];
    memcpy(insert_buffer, &vector[0], length);
    stream.write(insert_buffer, length);
} 

If I use const cVector3d vector in the parameter list, than I get a "& requires l-value" error.


Solution

  • The reason is in the documentation you linked:

    double &  operator[] (unsigned int index)
    double    operator[] (unsigned int index) const
    

    When you use the non-const version you get a l-value reference and you can take its address (which is the address of the referenced double). When you use the const-version, you get a temporary and the language forbids you to take its address.