Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Rust's Drop and C++'s destructor?

Tags:

c++

rust

While reading about the Drop trait, I found a lot of similarities between the drop method of Rust and the destructor in a C++. What is the difference between the two?

like image 703
ayush prashar Avatar asked Oct 17 '25 21:10

ayush prashar


1 Answers

In practice, there is no appreciable difference. Both are used to clean up the resources of a type when appropriate.

Resources will be cleaned up irrespective of implementation of the Drop trait, won't they?

Yes. The compiler essentially automatically implements Drop for any type where the programmer does not. This automatic implementation simply calls drop for each member variable in turn.

If you allocate a resource that Rust doesn't know about, such as allocating memory directly from an allocator, Rust won't know that the returned value needs to be dropped or how to do so. That's when you implement Drop directly.

See also:

  • Running Code on Cleanup with the Drop Trait
like image 51
Shepmaster Avatar answered Oct 20 '25 11:10

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!