gpt4 book ai didi

c++ - 通过 unsigned char 别名访问对象,加载和存储时会发生什么?

转载 作者:搜寻专家 更新时间:2023-10-31 01:30:19 25 4
gpt4 key购买 nike

在下面的示例中,数组不是通过其第一个元素访问的,而是通过概念上的数组别名访问的。然而,根据 C++17/[basic.lval]/8可以通过无符号字符访问对象的存储值。那么认为以下断言永远不会触发是正确的吗?

void g(){
unsigned char s[]={'X'};
unsigned char (*pointer_to_array_s)[1] = &s;
unsigned char *alias_to_array_s =
reinterpret_cast<unsigned char*>(pointer_to_array_s);
//alias_to_array_s is not a pointer whose value point to c[0] because an array
//and its firts element are not pointer interconvertible see [basic.compound]
//*alias_to_array_s aliases s;
assert(*alias_to_array_s=='X'); //may fire?
}

alias_to_array_s 不是指向 s 第一个元素的有效指针这一事实是由于 C++17 中引入的微妙之处,参见 Q&A .

现在假设我通过别名修改数组,我可以通过直接访问数组来检索这个修改吗?

void g(){
unsigned char s[]={'X'};
unsigned char (*pointer_to_array_s)[1] = &s;
unsigned char *alias_to_array_s =
reinterpret_cast<unsigned char*>(pointer_to_array_s);
*alias_to_array_s='Y'; //UB?
assert(s[0]=='Y');//may fire?
}

最佳答案

accessing is ok, but what can be asserted about the value? And for exemple I make a store through the object name, then a store through the aliasing pointer and then a load through the object name, is there no risk the compiler optimize away the last load and reflect it by an immediate which would equal the first store?

访问在 [defns.access] 中定义意思是:

read or modify the value of an object

因此通过 *alias_to_array_s='Y'; 修改值与读取它一样可以接受。

允许编译器通过 as-if 规则优化加载/存储。您的程序没有任何可观察到的行为。如果断言通过,编译器可以自由地将 g() 替换为空主体,并且根本不调用它。如果您真的担心编译器会重新排序加载/存储,您应该使用 volatile 或查看内存屏障。

关于c++ - 通过 unsigned char 别名访问对象,加载和存储时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48186273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com