why cant I use const arguments in memcpy?

天涯浪子 提交于 2019-12-20 02:27:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!