簡體   English   中英

嘗試將uint *&用作const單位*&失敗:從類型'uint8_t *的表達式中無效初始化類型'const uint8_t *&'的引用

[英]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*

以下代碼無法為我編譯(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()可行,但我想了解為什么

傳遞uint8_t *作為const uint8_t *&參數將允許函數將const uint8_t *&替換為unint8_t * const uint8_t * 現在,在調用者期望可修改的uint8_t *的地方有一個const uint8_t * uint8_t * 這不會保存,因為在函數返回之后,調用者可能會修改指向的數據。

問題與本“ C ++常見問題”精簡版部分中的問題相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM