gpt4 book ai didi

C++ 变量别名——那到底是什么,为什么关闭它会更好?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:48 25 4
gpt4 key购买 nike

我读过这篇文章 Surviving the Release Version .

在“Aliasing bugs”条款下它说:

You can get tighter code if you tell the compiler that it can assume no aliasing....

我也读过 Aliasing (computing) .

究竟什么是变量别名?我理解这意味着使用指向变量的指针是一个别名,但是,它如何/为什么会产生严重影响,或者换句话说 - 为什么告诉编译器它可以假设没有别名会让我得到一个“更严格的代码”

最佳答案

别名是指您对同一底层内存有两个不同的引用。考虑这个虚构的例子:

int doit(int *n1, int *n2)
{
int x = 0;

if (*n1 == 1)
{
*n2 = 0;

x += *n1 // line of interest
}

return x;
}

int main()
{
int x = 1;

doit(&x, &x); // aliasing happening
}

如果编译器必须允许别名,则需要考虑 n1 == n2 的可能性。因此,当它需要在“感兴趣的行”处使用 *n1 的值时,需要考虑它被 *n2 = 0 行更改的可能性.

如果编译器可以假定没有别名,它可以在“感兴趣的行”处假定 *n1 == 1(否则我们不会在 if 中).然后优化器可以使用此信息来优化代码(在这种情况下,将“感兴趣的行”从跟随指针并进行通用添加更改为使用简单的增量)。

关于C++ 变量别名——那到底是什么,为什么关闭它会更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2945343/

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