我在一些遺留的源代碼的行:鑄造焦炭[]到usigned INT給出:提領類型-punned指針將打破嚴格走樣規則
#define MAXMSG 1024
...
char m_recvBuf[MAXMSG];
unsigned int msgLength = ntohl(*((unsigned int *)m_recvBuf));
這產生以下警告:
x.cpp: In member function ‘bool xx::cccc(std::string&)’:
x.cpp:308: warning: dereferencing type-punned pointer will break strict-aliasing rules
我該如何擺脫這個警告?
我編譯行:
g++ -c -g -O2 -Wall -DDEBUG_ON -D_VERSION_=\"1.0.0\" `xml2-config --cflags` -I../src -I./common -I. -I../../test/ -o common/xx.o common/xx.cpp
$ g++ --version
g++ (GCC) 4.4.6 20110731 (Red Hat 4.4.6-3)
@MarcoA。請檢查我的更新 – Patryk 2014-08-28 10:35:32
使用編譯器選項'-fno-strict-aliasing'。這段代碼違反了標準,並且在-O3模式下,gcc可能會完全優化它,但是'-fno-strict-aliasing'選項會導致它的行爲就像您要訪問char緩衝區中的內存一樣。 – 2014-08-28 10:38:40
您也可以考慮修復代碼,例如'unsigned int msgLength; memcpy(&msgLength,m_recvBuf,sizeof msgLength); msgLength = ntohl(msgLength);',或者甚至更好,做一個便攜式轉換 – 2014-08-28 10:40:41