0

以下代码无法为我编译(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() 可以,但我想了解原因

4

1 回答 1

4

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

问题与此 C++ FAQ lite section中的问题相同。

于 2012-10-16T12:17:05.850 回答