gpt4 book ai didi

c++ - g++ 的严格别名警告准确性

转载 作者:行者123 更新时间:2023-11-30 02:19:45 26 4
gpt4 key购买 nike

GCC's documentation表示 -Wstrict-aliasing=3 是最准确的级别,较低的级别更有可能给出误报。

我相信以下示例都违反了严格的别名规则:

float violate1(float a_float)
{
float * f_data(&a_float);
int * i_data((int *)f_data);
int value(*i_data);
return value + a_float;
}

float violate2(float a_float)
{
int * i_data((int *)&a_float);
int value(*i_data);
return value + a_float;
}

float violate3(float *f_data)
{
int * i_data((int *)f_data);
int value(*i_data);
return value + *f_data;
}

然而,当使用 -Wstrict-aliasing=1 时,g++ 只会对它们全部发出警告。使用 -Wstrict-aliasing=3 不会发出警告:https://godbolt.org/g/aox2S1

这些例子实际上不是违规,还是 GCC 的警告不是违规的可靠指示?

最佳答案

严格别名规则在 [basic.lval] 中用非常明确的术语说明了

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • the dynamic type of the object [...]

这意味着 violate1violate2 是同一件事并且必然是违规。

对象指针 can be casted到和从另一个任意对象指针类型,结果是原始指针。在 violate3 中,如果 f_data 是之前转换为 float*int*,则不会违反 *i_data,但在 *f_data

处会违规

关于c++ - g++ 的严格别名警告准确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50396107/

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