Implementing drop and dangling references

I need to run an action when the item is dropped by implementing drop but I am not sure if I implement drop myself how to actually drop the value.
I plan to create a wrapper such as

use crate::User;
struct MyDroppableUser(pub User);
impl Drop for MyDroppableUser{

I want to reset all subscriptions of users when MyDroppableUser goes out of context.

So how can I implement drop without creating dangling pointers?

If you don't have any unsafe code, you aren't going to be creating dangling pointers with your destructor.

so I am not opting out default dropping behaviour by implementing custom drop right ?

Correct. After your drop method runs, the destructor of each field will run.



This is also explicitly documented.

1 Like

I read that first but it is really confusing

here the doc says the destructor runs or the value gets dropped not both at the same time.

1 Like

"Or" here means "in other words".

Okay, I also find that really confusing. A PR to update the wording would probably be in order.


oh, that makes much more sense :smiley: I thought if a custom destructor is provided that is run leaving cleaning up memory to implementer "or" it is run by default as default drop implementation

In general, Rust is designed with the principle of least surprise in mind, i.e., you can generally expect that the default behavior of some language feature is the right thing to do, and that you don't have to actively prevent yourself from shooting yourself in the foot. Of course no language is perfect, and there may be exceptions and perhaps non-obvious details, but memory management is a core value in Rust, so it is probably the most well-fleshed-out aspect of the language.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.