Constants live for the entire lifetime of a program. More specifically, constants in Rust have no fixed address in memory. This is because they’re effectively inlined to each place that they’re used. References to the same constant are not necessarily guaranteed to refer to the same memory address for this reason.
我只见过 C++ 中的“内联函数”,但从未见过内联常量值。对初学者友好的解释是什么?
我也对“内存中没有固定地址”感到困惑。这是否意味着每次我们使用 const
值时,堆栈 上的一个值都被分配给这个表达式,并且在表达式执行完毕后,它将是 销毁?
最佳答案
I've only seen "inline functions" in C++, but never inline constant values.
Rust 中最接近 const
的是 C++ 中的 enum
。
What is a beginner friendly explanation of how this works?
简单的初学者解释是:它只是工作,不要担心细节。
I'm also confused by "no fixed address in memory". Does that mean every time we use a
const
value, a value on the stack is allocated just for this expression and after the expression is done executing, it'll be destroyed?
是的。或许。没有。
它的意思和 jar 头上写的一模一样:不作任何保证。这让编译器有最大的自由来优化事物。
好吧,一切都很好,但是......到底发生了什么?
在实践中,有两种情况:
- 这个值很简单:它甚至不接触堆栈,而是直接在程序集中硬编码。例如,这最有可能发生在整数上。
- 值不是那么简单:它是在只读内存中创建的,并从那里引用/复制。堆栈上的多个副本将具有不同的地址。
简单是什么意思?这得看情况。对于每个调用站点,编译器可能会决定是否“足够简单”,这是接近内联的地方。
Does that mean every time we use a
const
value, a value on the stack is allocated just for this expression and after the expression is done executing, it'll be destroyed?
它不会被破坏。 const
变量不能具有实现 Drop
的类型。当不再使用该值时,它就会被遗忘。如果它曾经占用堆栈上的内存,则该内存将在稍后的某个时间被覆盖。
关于rust - 内联 Rust 中的常量值是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40148175/