使用std :: ptr ::在rust中阅读时双重错误
我正在尝试从指针中读取一个值,但我总是会收到双重
错误。你们知道一种解决方法吗?我正在使用 mem ::忘记
来阻止免费操作,但我仍然得到相同的结果。
use std::ptr;
use std::mem;
fn main() {
let test = String::from("hello!");
println!("{}", get_value_from_ptr(&test));
println!("{}", get_value_from_ptr(&test));
}
fn get_value_from_ptr<T>(val: &T) -> T {
let value = unsafe { ptr::read(val) };
mem::forget(&value);
value
}
错误:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.26s
Running `target/debug/playground`
free(): double free detected in tcache 2
timeout: the monitored command dumped core
/playground/tools/entrypoint.sh: line 11: 8 Aborted
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
mem :: nove()
必须采用拥有的值。如果您为其提供参考,它将忘记参考 - 这是毫无意义的,因为无论如何都没有drop
胶水。您必须mem ::忘记(value)
而不是mem ::忘记(&amp; value)
,但是随后您移出value ,您无法返回。
您要做的是从根本上不可能的。如果值不实现
复制
,则不能很好地复制一个值。即使您立即nove> nove()
it( ptr :: read()它也可能使原始值无效。 com/rust-lang/unsafe-code-guidelines/essument/307“ rel =“ nofollow noreferrer”>尚未确定)。之后使用它是一个非启动器。mem::forget()
must take an owned value. If you provide it with a reference, it'll forget the reference - which is meaningless since references do not have aDrop
glue anyway. You'll have tomem::forget(value)
and notmem::forget(&value)
, but then you move out ofvalue
and you cannot return it.What you're trying to do is fundamentally impossible. You cannot duplicate a value soundly if it does not implement
Copy
. Even justptr::read()
ing it may invalidate the original value, even if you immediatelyforget()
it (this is not decided yet). Using it after is a non-starter.