文字配列を他の型にキャストする場合、厳密なエイリアシング規則が混乱します。私はどのオブジェクトをキャストすることが許可されていることを知っているは、文字の配列ですが、私は別の方法で起こるか分からない。char配列から*をキャストするときの厳密なエイリアシング規則は何ですか?
は、このを見てみましょう:G ++使用してコンパイルする
#include <type_traits>
using namespace std;
struct{
alignas (int) char buf[sizeof(int)]; //correct?
} buf1;
alignas(int) char buf2[sizeof(int)]; //incorrect?
struct{
float f; //obviously incorrect
} buf3;
typename std::aligned_storage<sizeof(int), alignof(int)>::type buf4; //obviously correct
int main()
{
reinterpret_cast<int&>(buf1) = 1;
*reinterpret_cast<int*>(buf2) = 1;
reinterpret_cast<int&>(buf3) = 1;
reinterpret_cast<int&>(buf4) = 1;
}
- 本体のみの第二と第三のライン上の警告で5.3.0結果:
$ g++ -fsyntax-only -O3 -std=c++14 -Wall main.cpp
main.cpp: In function ‘int main()’:
main.cpp:25:30: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
*reinterpret_cast<int*>(buf2) = 1;
^
main.cpp:26:29: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
reinterpret_cast<int&>(buf3) = 1;
^
は、そのラインで正しいのgccです1と4は正しいですが、2と3は違いますか?私は確かに4行目が正しいと確信していますが(それはaligned_storage
のためです)、ここでは何のルールがありますか?
他の方法は許可されていません。 –
これらはすべてUBです(あなたが "明らかに正しい"ことを意味するかどうかは分かりません) –