讓我們假設我有以下代碼:指向對象表示元素的指針或指向提供的存儲元素的指針?
int* p = new (new unsigned char[3*sizeof(int)]) int{};
unsigned char* b = reinterpret_cast<unsigned char*>(p);
auto b2 = b + 2*sizeof(int);//it is UB if compilers do not assume that
//b is pointer to an unsigned char[3*sizeof(int)]
int* p2 = new (b2) int{};
如果b
不是指針到3*sizeof(int)
無符號字符的陣列,對於*p
提供存儲,則段[expr.add]作爲C++標準意味着b+2*sizeof(int)
是未定義的行爲(UB)。否則,如果編譯器必須假定b
也是指向爲*p
提供存儲的無符號字符數組的指針,那麼它不是UB。
所以它在標準中指定的編譯器必須假定b
是一個指針,它指向的*p
提供存儲unsigned char[3*sizeof(int)]
?