gpt4 book ai didi

rust - 为什么有时 my_arc_mutex.clone() 在完成使用之前会被释放?

转载 作者:行者123 更新时间:2023-12-04 07:45:24 26 4
gpt4 key购买 nike

我收到了这个错误:

   --> src/client.rs:189:22
|
189 | let client = client.clone().lock().unwrap();
| ^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
这个函数太大了,我无法发布一个最小可重现的例子:
async fn send_and_expect<T: OnEvent<T>>(
client: Arc<Mutex<Self>>,
request: rtsp_types::Message<Body>,
unauthorized_retry: i32,
) -> std::result::Result<rtsp_types::Response<Body>, ClientActionError>
where
RtspMachine: OnEvent<T>,
T: From<Response>,
{
let expected_cseq = client_parse_cseq(&request)?;
let mut client = client.lock().unwrap();
如果我干脆不克隆,也就是做 let mut client = client.lock().unwrap(); ,它编译。但我想知道为什么 clone()使这个错误发生。
我试图重现问题以在此处发布:
use std::sync::{Arc, Mutex};
fn main() {
let a = Arc::new(Mutex::new(0));
a.clone().lock().unwrap();
}
但这可以编译。
怎么了?为什么会 client.clone()有时在完成使用之前被释放,但有时不是?

最佳答案

不幸的是,您的简短示例太短了,因为它从不绑定(bind) unwrap ped MutexGuard。要重现错误,我们需要添加一个绑定(bind) (playground):

use std::sync::{Arc, Mutex};

fn main() {
let a = Arc::new(Mutex::new(0));
let _b = a.clone().lock().unwrap();
}
rustc现在大喊大叫:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:5:13
|
5 | let _b = a.clone().lock().unwrap();
| ^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
6 | }
| - borrow might be used here, when `_b` is dropped and runs the `Drop` code for type `MutexGuard`
|
= note: consider using a `let` binding to create a longer lived value
那么为什么借用检查员对我们大喊大叫呢?请记住 Mutex::lock(&self) 引用 Mutex .此引用源自 Arc .但是, clone d 变体只存在到语句结束:没有绑定(bind)到 a.clone() ,它在分号处消失了。
简单的解决方法是绑定(bind) a.clone() .通常,您会重复使用相同的标识符,如 Rust's Arc example ( playground):
use std::sync::{Arc, Mutex};

fn main() {
let a = Arc::new(Mutex::new(0));
let a = a.clone();
let _b = a.lock().unwrap();
}
虽然这在单个 main 中可能看起来很奇怪函数,在 move 时更常见将值转换为闭包。
“现在等一下”,你可能会说。 “这是一个共享引用,为什么我不能继续使用它?还有 a在同一个范围内!”虽然这可能是真的,但它也是一个陷阱。如果 .clone().lock()行要编译,然后我们可以创建一个 use-after-free 错误:
let a = Arc::new(Mutx::new(0));
let b = a.clone().lock().unwrap(); // reference counter increased and decreased by 1
drop(a); // reference counter -> 0: value gets freed
*b = 10; // whoops!

关于rust - 为什么有时 my_arc_mutex.clone() 在完成使用之前会被释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67223689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com