【问题标题】:Trying to use a uint*& as a const unit*& fails: invalid initialization of reference of type ‘const uint8_t*&’ from expression of type ‘uint8_t*尝试使用 uint*& 作为 const unit*& 失败:从类型为“uint8_t*”的表达式中对类型为“const uint8_t*&”的引用进行无效初始化
【发布时间】:2012-10-16 12:00:31
【问题描述】:

以下代码无法为我编译(gcc 4.6.3,Ubuntu 12.04):

#include <inttypes.h>
#include <stdio.h>

static inline void adjustBuffer(const uint8_t *&buf, size_t &bufSize, size_t len)
{
    buf += len;
    bufSize -= len;
}                

uint16_t packInt(uint8_t *&buf, size_t &bufSize, int value)
{
    size_t valueSize = sizeof(int);
    *reinterpret_cast<int *>(buf) = value;
    adjustBuffer(buf, bufSize, valueSize);
    return valueSize;
}

bool unpackInt(const uint8_t *&buf, size_t &bufSize, int &value)
{
    value = *reinterpret_cast<const int*>(buf);
    adjustBuffer(sizeof(int));
    return true;
}

int main()
{
    static const size_t BufSize = 100;
    size_t bufSize = BufSize;
    uint8_t buf[BufSize];
    uint8_t *buf_ptr = buf;
    packInt(buf_ptr, bufSize, 1);
    bufSize = BufSize;
    int x;
    unpackInt(buf, bufSize, x);
    return 0;
}

我收到以下错误:

$ make CXXFLAGS="-Wall -g" ref_to_ptr
g++ -Wall -g    ref_to_ptr.cpp   -o ref_to_ptr
ref_to_ptr.cpp: In function ‘uint16_t packInt(uint8_t*&, size_t&, int)’:
ref_to_ptr.cpp:15:41: error: invalid initialization of reference of type ‘const uint8_t*& {aka const unsigned char*&}’ from expression of type ‘uint8_t* {aka unsigned char*}’
ref_to_ptr.cpp:5:20: error: in passing argument 1 of ‘void adjustBuffer(const uint8_t*&, size_t&, size_t)’
ref_to_ptr.cpp: In function ‘bool unpackInt(const uint8_t*&, size_t&, int&)’:
ref_to_ptr.cpp:22:29: error: invalid initialization of non-const reference of type ‘const uint8_t*& {aka const unsigned char*&}’ from an rvalue of type ‘unsigned int’
ref_to_ptr.cpp:5:20: error: in passing argument 1 of ‘void adjustBuffer(const uint8_t*&, size_t&, size_t)’
ref_to_ptr.cpp: In function ‘int main()’:
ref_to_ptr.cpp:35:30: error: invalid initialization of non-const reference of type ‘const uint8_t*& {aka const unsigned char*&}’ from an rvalue of type ‘uint8_t* {aka unsigned char*}’
ref_to_ptr.cpp:19:6: error: in passing argument 1 of ‘bool unpackInt(const uint8_t*&, size_t&, int&)’
make: *** [ref_to_ptr] Error 1

编译器似乎无法将 uint8_t* (uint8_t *&) 的引用分配给 const uint8_t *&(IIRC 是对 const 指针的引用)。首先,我不明白为什么它试图将指针分配给 uint8_t 而不是对指针的引用。其次,转换不应该工作吗?您可以将 uint8_t * 转换为 const uint8_t *,为什么不能转换对这两种类型的引用?

当然,添加一个接受 const uint8_t *& 的 adjustBuffer() 可以,但我想了解原因

【问题讨论】:

  • 删除 buf 上的 const 运算符,因为您实际上是在更改它
  • @Sednus const 用于指向的类型,而不是指针

标签: c++ pointers gcc reference constants


【解决方案1】:

将uint8_t * 作为const uint8_t *&amp; 参数传递将允许函数将unint8_t * 替换为const uint8_t *。现在在调用者期望可修改的uint8_t * 的地方有一个const uint8_t *。这不是保存,因为调用者可能会在函数返回后修改指向的数据。

问题和this C++ FAQ lite section一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多