为什么我不能在memcpy中使用const参数?

我有一个struct cVector3d ,我struct cVector3d它像这样的char数组:

 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); } 

如果我在参数列表中使用const cVector3d vector ,那么我得到一个“ & requires l-value ”错误。

原因在于您链接的文档:

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

当您使用非const版本时,您将获得l值引用,并且您可以获取其地址(这是引用的double的地址)。 当你使用const-version时,你得到一个临时版本,语言禁止你获取它的地址。

您的问题在文档中是这样的:

 double operator[] (unsigned int index) const 

如果你有一个const向量,operator []返回一个临时值。 你不能拿一个临时的地址。