rust - 内联 Rust 中的常量值是什么意思?

标签 rust constants inline

documentation for const :

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/

相关文章:

无法添加到 C 中的字符串文字以移动其索引

html - 如何删除 jquery UI datepicker 右侧的额外宽度?

rust - 将 `trait Bar: Foo {}` 保存到 `struct Abc<Foo>`

c++ - 常量函数参数作为静态数组大小?

generics - Rust:泛型必须实现 &xx[...]

constants - glsl 编译时除法 const

c++ - 内联函数上的 static_assert 给出错误

html - header 中的 Logo

static-libraries - Rust 静态库 "unlinked native library"警告

iterator - 为什么我们不实现 Iterator 中的所有函数来实现一个迭代器呢?