gpt4 book ai didi

ios - 编译器如何证明内存安全?

转载 作者:行者123 更新时间:2023-12-04 14:54:16 25 4
gpt4 key购买 nike

当我阅读 The Swift Programming Language: Memory Safety 时,我对 Conflicting Access to Properties 部分感到困惑。 :

The code below shows that the same error appears for overlapping writeaccesses to the properties of a structure that’s stored in a globalvariable.

var holly = Player(name: "Holly", health: 10, energy: 10)
balance(&holly.health, &holly.energy) // Error

In practice,most access to the properties of a structure can overlap safely. Forexample, if the variable holly in the example above is changed to alocal variable instead of a global variable, the compiler can provethat overlapping access to stored properties of the structure issafe:

func someFunction() {
var oscar = Player(name: "Oscar", health: 10, energy: 10)
balance(&oscar.health, &oscar.energy) // OK
}

In the example above, Oscar’s health and energy are passed as the two in-out parameters to balance(_:_:). The compiler can prove that memorysafety is preserved because the two stored properties don’t interactin any way.

编译器如何证明内存安全?

最佳答案

在函数范围内使编译器确定将在 struct 上执行哪些操作以及何时执行。编译器知道 structs 是如何工作的,以及函数内的代码如何以及何时(相对于调用函数的时间)执行。

在全局或更大的范围内,编译器无法看到可能修改内存的内容以及修改时间,因此它无法确保安全。

关于ios - 编译器如何证明内存安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68429581/

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