gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:29:27 27 4
gpt4 key购买 nike

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

#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”注释,它就可以正常工作。

但是,指针不应该隐式转换为 const 指针,然后引用吗?我期望它起作用是错误的吗?谢谢!

最佳答案

如果像您建议的那样将指针转换为 const 指针,则该转换的结果是一个临时值,一个右值。您不能将非常量引用附加到右值——这在 C++ 中是非法的。

例如,由于类似的原因,这段代码不会编译

int i = 42;
double &r = i;

尽管 int 类型可以转换为 double 类型,但这并不意味着您可以将 double & 引用附加到该转换的结果。

但是,可以将 const 引用(即对 const 类型的引用)附加到右值,这意味着这段代码可以完美编译

int i = 42;
const double &r = i;

在您的情况下,如果您将函数声明为

void PrintInt(const unsigned char* const& ptr) // note the extra `const`

代码将编译。

关于c++ - 为什么没有从指针到对 const 指针的引用的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2908244/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com