Optional pointer w/o leak

#1

I wanted to have a Option<Box<Other>> and access to the underlying boxed value. I’m currently holding a Option<*mut Other>, which though won’t have pointed memory released after anon_box.into_raw() (where anon_box = Box::new(other)), as the docs recommends to construct another box back with Box::from_raw(). So is there something phantom for not leaking heap memory?

0 Likes

#2

If you want to turn the Box<T> into a pointer, then you can use into_raw and then from_raw once you’re done with the pointer to drop the underlying value

0 Likes

#3

But it will drop earlier since the box won’t be in my longer-living struct. Or maybe I should do that in Drop explictly.

0 Likes

#4

Why do you need a Option<Box<Other>> rather than, e.g., a Option<&mut Other>? If your long-lived struct is what actually owns the allocation behind the raw pointer, then you shouldn’t try to create a Box from that allocation in other places. Keep the raw ptr there, and deallocate it in the long lived struct’s Drop impl.

3 Likes

#5

Truly I was referring to another struct, DisplayElement, which wraps it (Other) and holds other fields. Right, if Other were longer, then I could borrow it; but instead it’s owned by DisplayElement. The issue is since I want an optional Other, so that not all elements need to store additional fields (a.k.a. advanced fields).

I’m in a phone and I may install Termux later to check if it’ll work to implement the Drop trait.

0 Likes

#6

Can you provide an example of what you’re trying to achieve on the Rust playground, or at least sketch out some code here?

It’s a bit hard to tell what exactly is the problem. I also don’t quite understand why you need a *mut Other raw pointer to begin with - is there a reason DisplayElement can’t store an Option<Other> or Option<Box<Other>> (if you want/need Other on the heap)? So DisplayElement owns the Other - who else needs to use/borrow this Other? More elaboration would help, as mentioned.

0 Likes

#7

I’m in phone and that’s true. Well, here’s a code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=90bb207a2c7cef92768825dcfa3f513d

I thought it’d fail with Box. In my real code I’m using a Cell, but once I used it with Rc (Cell<Option<Rc<Advanced>>>) and it didn’t compile. So it looks like I may not need to use the raw pointer, but I’m afraid it won’t compile complaining about Copy. :confused:

0 Likes

#8

I don’t think you need the Cell wrapper. It seems you can just use something like:

struct DisplayElem {
    other: Option<Rc<Other>>,
}

struct Other {
    pub alpha: Cell<u8>,
    pub scale_x: Cell<f64>,
    pub scale_y: Cell<f64>,
}

I’m assuming here that you actually want the Rc over Other, and that you want interior mutability over the individual fields of Other.

With the above, your example becomes this.

0 Likes