为什么没有从指针到引用到 const 指针的隐式转换

2022-01-05 00:00:00 reference pointers c++

我将用代码说明我的问题:

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 中)时,我得到这个:错误 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 指针,如您所建议的,那么转换的结果是一个临时值,一个 rvalue.您不能将非常量引用附加到右值 - 这在 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`

代码将被编译.

相关文章