advance/smart-pointer/drop #749
Replies: 10 comments 24 replies
-
rust是如何做到不会在手动 |
Beta Was this translation helpful? Give feedback.
-
关于 Copy 和 Drop 互斥这一点,我个人觉得其实不止难以预测这一点。可以参考一下 StackOverflow 的回答:Why does Rust not allow the copy and drop traits on one type? |
Beta Was this translation helpful? Give feedback.
-
基本類型是同時實現了 Copy 和 Drop 嗎, 爲什麼它們可以 ? |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
在非主线程中,定义了一个实现 Drop 特征的对象变量(它内部申请了堆内存),原本是想在变量到达作用域结尾时被释放的,结果在此之前发生了 panic,此时不会调用 drop 释放堆内存,那是否就意味着内存泄露了呢? |
Beta Was this translation helpful? Give feedback.
-
stack unwrap。栈展开。发生异常时,在栈上的变量都会运行析构。直到异常被捕获。
主要目的是为了异常安全,分配的资源都释放掉。
cpp也有这技术。
…---- 回复的原邮件 ----
| 发件人 | Wenqing ***@***.***> |
| 日期 | 2023年06月05日 23:55 |
| 收件人 | ***@***.***> |
| 抄送至 | ***@***.***>***@***.***> |
| 主题 | Re: [sunface/rust-course] advance/smart-pointer/drop (Discussion #749) |
出于好奇心写了个测试:
use std::thread::spawn;#[derive(Debug)]structA{_strings:Vec<String>,}implA{fnnew(init_string:&str) -> Self{let strings = vec![init_string.to_owned()];Self{_strings: strings
}}}implDropforA{fndrop(&mutself){println!("dropped");}}fnmain(){let handle = spawn(move || {let a = A::new("hello");panic!("Oh no!");println!("{:?}", &a);});
handle.join().unwrap();}
运行结果:
thread '<unnamed>' panicked at 'Oh no!', src/main.rs:26:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
dropped
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Any { .. }', src/main.rs:29:19
所以,即使子线程panic了,变量也会被drop掉。
Rust牛逼。。。。
以及,我隐约记得当主线程退出时,OS自己也会检查下时候所有资源都被释放了?
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you commented.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
-
大佬们帮忙看下,这段代码为什么会报错啊? struct HasDrop1;
struct HasDrop2;
impl Drop for HasDrop1{
fn drop(&mut self){
println!("Dropping HasDrop1")
}
}
//如果移除下面的语句就不会报错
//--------------------------
impl Drop for HasDrop2{
fn drop(&mut self){
println!("Dropping HasDrop2")
}
}
//---------------------------
struct HasTwoDrops{
one:HasDrop1,
two:HasDrop2
}
impl Drop for HasTwoDrops {
fn drop(&mut self) {
println!("Dropping HasTwoDrops!");
}
}
fn main(){
let one=HasDrop1;
let two;
{
let _x=HasTwoDrops{
one,
two:HasDrop2,
};
two=_x.two;
}
println!("Running! ");
let z=two;
} 报错信息:
但是如果移除下面代码就不报错了 impl Drop for HasTwoDrops {
fn drop(&mut self) {
println!("Dropping HasTwoDrops!");
}
} |
Beta Was this translation helpful? Give feedback.
-
drop函数跟真正释放内存的函数是什么关系呢?如果我在drop函数里只写了print函数,对象的内存会被释放吗? |
Beta Was this translation helpful? Give feedback.
-
Drop:他来了,然后带走了一切。 |
Beta Was this translation helpful? Give feedback.
-
实现Drop特征需要可变引用,但如果对象本身是不可变的,如何有可变引用?(hh..) |
Beta Was this translation helpful? Give feedback.
-
advance/smart-pointer/drop
https://course.rs/advance/smart-pointer/drop.html
Beta Was this translation helpful? Give feedback.
All reactions