问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/17669913/why-cant-i-use-const-arguments-in-memcpy