1

How can I understand the below piece of Rust code with the corresponding C++ concept?

Below is my analysis regarding this snippet of code:

This is a reference to an array in Rust, but as we know, a reference in Rust is similar to a pointer in C++ which has top-level constness and bottom-level constness. But in C++, we cannot write it that way, meaning we cannot write a pure rvalue reference of an array. We can only write something like int &&x = 10 which indicates it is an rvalue-reference to a numeric value, namely a reference to a temporary value. If we use the pointer concept in C++ to imitate this Rust behavior, we cannot write a pointer directly pointed to a temporary value, right? So, how should I understand this?

fn main() {
    let x = &[1, 2, 4];
}
Jason Yu
  • 1,886
  • 16
  • 26
  • 1
    What do you mean by "top-level constness and bottom-level constness"? – trent Apr 13 '21 at 14:05
  • Is this the answer to your question: [Why is it legal to borrow a temporary?](https://stackoverflow.com/questions/47662253/why-is-it-legal-to-borrow-a-temporary) – trent Apr 13 '21 at 14:06
  • @trentcl, Yes, seems this is what I need. – Jason Yu Apr 13 '21 at 14:08
  • C++ arrays have all sorts of weirdness around them, but Rust's arrays are first class citizens that behave just like any other type, so in Rust [Why is it legal to borrow a temporary?](https://stackoverflow.com/questions/47662253/why-is-it-legal-to-borrow-a-temporary) applies just as much to arrays as to any other type. – mcarton Apr 13 '21 at 14:12
  • Just to complete the application of the other answer here: you can understand this Rust code as being roughly equivalent to [this C++ code](http://coliru.stacked-crooked.com/a/1a6c3964e5aa3057) – trent Apr 13 '21 at 14:14
  • @trentcl: Except there `_unnamed__x` is in main's stack frame, whereas the `[1, 2, 4]` in Rust would be in the data segment? – eggyal Apr 13 '21 at 14:36
  • 1
    @eggyal You're probably thinking of [rvalue static promotion](https://stackoverflow.com/q/50345139/3650362), which only kicks in when the reference is forced to be `'static`. This reference isn't `'static`, so `[1, 2, 4]` is a "normal" temporary, not a static. See also [What are the semantics of mutably borrowing a literal in Rust?](https://stackoverflow.com/q/51344979/3650362) (mutably borrowing a temporary can't be implemented by putting it in the data segment). – trent Apr 13 '21 at 14:43
  • Ah, yeah, is obvious now you mention mutable borrows. Thanks. :-) – eggyal Apr 13 '21 at 14:45
  • slices are just: ```c++ template struct Slice { size_t len; T* buf; } ```, but all this collapsed into a type of pointer – cdecompilador Apr 13 '21 at 19:50

0 Answers0