study_example/smart_pointer/
drop_trait.rs

1use std::ops::Drop;
2struct XY {
3    x: i32,
4    y: i32,
5}
6
7struct Point {
8    xy: XY,
9    ecc: String,
10}
11
12impl Drop for XY {
13    fn drop(&mut self) {
14        println!("dropping XY:({}, {})", self.x, self.y);
15    }
16}
17
18impl Drop for Point {
19    fn drop(&mut self) {
20        println!(
21            "dropping point ecc of {} with XY:({}, {})",
22            self.ecc, self.xy.x, self.xy.y
23        );
24    }
25}
26
27/// 运行结果如下,这里的顺序与书本内容不符合?
28/// dropping point ecc of ecdsa with XY:(1, 1)
29/// dropping XY:(1, 1)
30/// dropping point ecc of ecdsa with XY:(2, -1)
31/// dropping XY:(2, -1)
32/// 将变量名从_换成pointer1和pointer2结果与书本顺序介绍相同如下
33/// ```txt
34/// dropping point ecc of ecdsa with XY:(2, -1)
35/// dropping XY:(2, -1)
36/// dropping point ecc of ecdsa with XY:(1, 1)
37/// dropping XY:(1, 1)
38/// ```
39/// 原因可能是编译器做的,当用_意味着后续不会使用提前释放了内存?
40fn drop_struct_test() {
41    let pointer1 = Point {
42        xy: XY { x: 1, y: 1 },
43        ecc: String::from("ecdsa"),
44    };
45    let pointer2 = Point {
46        xy: XY { x: 2, y: -1 },
47        ecc: String::from("ecdsa"),
48    };
49    // error[E0040]: explicit use of destructor method
50    // pointer1.drop();
51}
52
53/// 运行结果如下
54/// ```txt
55/// [early_drop_with_stddrop_test] pointer crated.
56/// dropping point ecc of ecdsa with XY:(1, 1)
57/// dropping XY:(1, 1)
58/// [early_drop_with_stddrop_test] pointer before the end of fn
59/// ```
60fn early_drop_with_stddrop_test() {
61    let pointer = Point {
62        xy: XY { x: 1, y: 1 },
63        ecc: String::from("ecdsa"),
64    };
65    println!("[early_drop_with_stddrop_test] pointer crated.");
66    std::mem::drop(pointer);
67    println!("[early_drop_with_stddrop_test] pointer before the end of fn");
68}
69
70pub fn drop_trait_study() {
71    drop_struct_test(); // 结束函数的scope的时候,调用对应的drop
72    early_drop_with_stddrop_test();
73}