![](/img/trans.png)
[英]Is this casting and std::launder C++ standard conform and no undefined behavior
[英]Why is this std::launder example undefined behavior?
這是我不明白的示例部分:
struct Y
{
int z;
};
int main()
{
alignas(Y) std::byte s[sizeof(Y)];
Y *q = new (&s) Y{2};
const int f = reinterpret_cast<Y *>(&s)->z; // Class member access is undefined behavior:
// reinterpret_cast<Y*>(&s) has value "pointer to s"
// and does not point to a Y object
}
整個示例位於https://en.cppreference.com/w/cpp/utility/launder 。
我不明白為什么使用reinterpret_cast<Y *>(&s)->z
是未定義的行為。 我們已經在所謂的“指向 s 的指針”處構造了一個 Y 對象,並將其重新解釋為Y*
,那么為什么它仍然說“它不指向一個 Y 對象”呢?
&s
是指向std::byte[sizeof(Y)]
的指針,而不是Y
。 這意味着使用&s
作為Y*
是未定義的行為,因為它違反了別名規則。 即使有一個Y
住在那里, reinterpret_cast
的規則(特別是類型別名部分)也不允許您訪問該對象,因為它無法知道那里實際上有一個對象。
引入std::launder
是為了明確允許您將返回的指針視為指向對象的有效指針,而不是指向對象所在存儲的指針。本質上,它是類型別名規則的顯式覆蓋。 你用它告訴編譯器你知道指針確實指向一個有效的對象,如果你撒謊,那么你又回到了未定義的行為領域。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.