Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate structs on the heap without taking up space on the stack in stable Rust?

Tags:

rust

In this code...

struct Test { a: i32, b: i64 }
    
fn foo() -> Box<Test> {              // Stack frame:
    let v = Test { a: 123, b: 456 }; // 12 bytes
    Box::new(v)                      // `usize` bytes (`*const T` in `Box`)
}

... as far as I understand (ignoring possible optimizations), v gets allocated on the stack and then copied to the heap, before being returned in a Box.

And this code...

fn foo() -> Box<Test> {
    Box::new(Test { a: 123, b: 456 })
}

...shouldn't be any different, presumably, since there should be a temporary variable for struct allocation (assuming compiler doesn't have any special semantics for the instantiation expression inside Box::new()).

I've found Do values in return position always get allocated in the parents stack frame or receiving Box?. Regarding my specific question, it only proposes the experimental box syntax, but mostly talks about compiler optimizations (copy elision).

So my question remains: using stable Rust, how does one allocate structs directly on the heap, without relying on compiler optimizations?

like image 321
mrnateriver Avatar asked Dec 08 '19 06:12

mrnateriver


People also ask

Are structs allocated on the heap Rust?

Anything inside a Box , Vec , Rc , or Arc will be put on the heap, but the actual Box struct itself (i.e. the pointer) will live on the stack.

Are structs allocated on the heap?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.

Is the heap slower than the stack?

Dynamic memory allocation and deallocation are very slow operations when compared to automatic memory allocation and deallocation. In other words, the heap is much slower than the stack.


1 Answers

Is there a way to allocate directly to the heap without box?

No. If there was, it wouldn't need a language change.

People tend to avoid this by using the unstable syntax indirectly, such as by using one of the standard containers which, in turn, uses it internally.

See also:

  • How to allocate arrays on the heap in Rust 1.0?
  • Is there any way to allocate a standard Rust array directly on the heap, skipping the stack entirely?
  • What does the box keyword do?
  • What is the <- symbol in Rust?
like image 74
Shepmaster Avatar answered Sep 19 '22 09:09

Shepmaster