相关疑难解决方法(0)

Rust如何知道是否在堆栈展开期间运行析构函数?

该文档mem::uninitialized指出了使用该函数危险/不安全的原因:调用drop未初始化的内存是未定义的行为.

因此,我相信这段代码应该是未定义的:

let a: TypeWithDrop = unsafe { mem::uninitialized() };
panic!("=== Testing ==="); // Destructor of `a` will be run (U.B)
Run Code Online (Sandbox Code Playgroud)

但是,我编写了这段代码,它在安全的Rust中运行,并且似乎没有受到未定义的行为的影响:

#![feature(conservative_impl_trait)]

trait T {
    fn disp(&mut self);
}

struct A;
impl T for A {
    fn disp(&mut self) { println!("=== A ==="); }
}
impl Drop for A {
    fn drop(&mut self) { println!("Dropping A"); }
}

struct B;
impl T for B {
    fn disp(&mut self) { println!("=== B ==="); }
}
impl …
Run Code Online (Sandbox Code Playgroud)

destructor stack-unwinding undefined-behavior rust

21
推荐指数
2
解决办法
1891
查看次数