问题描述
我将用代码说明我的问题:
I'll illustrate my question with code:
#include <iostream>
void PrintInt(const unsigned char*& ptr)
{
int data = 0;
::memcpy(&data, ptr, sizeof(data));
// advance the pointer reference.
ptr += sizeof(data);
std::cout << std::hex << data << " " << std::endl;
}
int main(int, char**)
{
unsigned char buffer[] = { 0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22, };
/* const */ unsigned char* ptr = buffer;
PrintInt(ptr); // error C2664: ...
PrintInt(ptr); // error C2664: ...
return 0;
}
当我运行这个代码(在VS2008)我得到这个:error C2664: 'PrintInt':不能将参数1从'unsigned char *'转换为'const unsigned char *&'。如果我取消注释const注释它工作正常。
When I run this code (in VS2008) I get this: error C2664: 'PrintInt' : cannot convert parameter 1 from 'unsigned char *' to 'const unsigned char *&'. If I uncomment the "const" comment it works fine.
但是,应该不应该指针隐式转换为const指针,然后引用?我错了期望这个工作吗?感谢!
However shouldn't pointer implicitly convert into const pointer and then reference be taken? Am I wrong in expecting this to work? Thanks!
推荐答案
如果指针被转换为const指针,那么转换的结果是临时的值,右值。你不能附加一个非const引用到右值 - 这在C ++是非法的。
If the pointer gets converted to a const pointer, as you suggest, then the result of that conversion is a temporary value, an rvalue. You cannot attach a non-const reference to an rvalue - it is illegal in C++.
例如,此代码不会由于类似的原因进行编译
For example, this code will not compile for a similar reason
int i = 42;
double &r = i;
即使类型 int
double
,但这并不意味着您可以对该转换的结果附加 double&
引用。
Even though type int
is convertible to type double
, it still doesn't mean that you can attach a double &
reference to the result of that conversion.
但是,const引用(即引用到const类型的引用)可以附加到右值,这意味着该代码将编译完全精细
However, a const reference (i.e. a reference of reference-to-const type) can be attached to an rvalue, meaning that this code will compile perfectly fine
int i = 42;
const double &r = i;
在您的情况下,如果您将函数声明为
In your case if you declare your function as
void PrintInt(const unsigned char* const& ptr) // note the extra `const`
代码将编译。
这篇关于为什么没有从指针到引用的const指针的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!