How it works...

This example, adapted with slight changes from the second edition of the Rust book (https://doc.rust-lang.org/book/second-edition/), shows you how to start the implementation of a custom smart pointer. In our case, all it does is print the Debug information of the data stored when its dropped [26]. We do this by implementing the Drop trait with its single drop function [25], which the compiler automatically calls whenever a variable is dropped. All smart pointers are implemented this way.

The moment of a variable drop will nearly always be when it leaves its scope. For this reason, we cannot call the drop function directly[38]. The compiler will still call it when it exits its scope, so the cleanup will happen twice, resulting in undefined behavior. If you need to drop a variable early, you can tell the compiler to do so for you by calling std::mem:drop on it [41].

Variables that exit their scope are dropped in a LIFO way: Last In, First Out. That means that the last variable to be declared will be the first one to be dropped. If we allocate the variables a, b, c, and d in exactly that order, they will be dropped in the order d, c, b, a. In our example, we drop c early[41], so our order becomes c, d, b, a instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.60.249