user494461
user494461

Reputation:

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.

Upvotes: 3

Views: 654

Answers (2)

AliciaBytes
AliciaBytes

Reputation: 7429

Your problem is this here in the documentation:

double  operator[] (unsigned int index) const

The operator[] returns a temporary if you got a const vector. And you can't take the address of a temporary.

Upvotes: 1

syam
syam

Reputation: 15089

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.

Upvotes: 4

Related Questions