我有一個結構,其中包含一個位元組陣列和幾個對陣列中各個點的型別轉換參考。位元組 4:7 可以解釋為浮點數、int32_t 或 uint32_t,由通過串行連接接收的資料包中的其他欄位確定。為了使訪問簡單(例如message.argument.F對于浮點解釋),我對間接型別轉換指標進行了多次參考。但是當我運行程式時,我遇到了一個段錯誤,試圖寫入結構中的參考。據我所知,問題與容器有關,如本示例片段所示(cpp shell:http ://cpp.sh/3vmoy ):
#include <iostream>
#include <cstring>
using namespace std;
#define PACKET_SIZE 9
#define ARG_I 4
struct Message{
uint8_t bytes[PACKET_SIZE];
uint8_t* argbytes = static_cast<uint8_t*>(argp);
float& argf = *static_cast<float*>(argp);
void* argp = &bytes[ARG_I];
} message;
int main(){
// USING STRUCT
cout << "Using message struct" << endl;
cout << message.argp << endl; // the pointer at index stored in struct
cout << static_cast<float*>(message.argp) << endl; // casting the pointer to a float* - should be the same
cout << &message.argf << endl; // the address of the float reference cast from argp, ** should be the same BUT IS NOT **
// RAW VARS
uint8_t bytes[PACKET_SIZE];
void* argp = &bytes[ARG_I];
float& argf = *static_cast<float*>(argp);
cout << endl << "using raw vars" << endl;
cout << argp << endl; // a pointer to a byte in an array of bytes.
cout << static_cast<float*>(argp) << endl; // the same pointer cast as a float*
cout << &argf << endl; // the address of a float reference cast from argp, **should be the same AND IS.**
}
I expect to see the same address for the pointer, a typecast pointer, and the address of the reference for the indirected pointer. I do see that if I create an array and the pointer/reference as standalone variables, but not for the same declarations in a struct. What arcane knowledge do I lack to explain this behavior (or what silly thing have I overlooked?)
My thoughts for fixing this are to a) ignore it and just typecast the pointer as necessary instead, or b) make some setter/getter functions to access the argument portion of the serial "packet".
uj5u.com熱心網友回復:
兩個替代代碼塊之間有兩個主要的、根本的區別。
void* argp = &bytes[ARG_I];
float& argf = *static_cast<float*>(argp);
在這里, this 先構造和初始化argp,然后argf.
float& argf = *static_cast<float*>(argp);
void* argp = &bytes[ARG_I];
在這里,它沒有。
這首先初始化argf,然后argp。這樣做的后果應該是很明顯的。
注意:我在這里忽略了所有違反別名規則的行為,這可能是進一步未定義行為的來源。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450302.html
標籤:c pointers reference type-conversion
下一篇:在const參考中呼叫函式
