如何决定何时将函数标记为不安全? [英] How do I decide when to mark a function as unsafe?

查看:27
本文介绍了如何决定何时将函数标记为不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候将函数标记为 unsafe 与仅使用 unsafe 块比较合适?我在阅读另一个答案时看到了这个功能:

When is it appropriate to mark a function as unsafe versus just using an unsafe block? I saw this function while reading another answer:

unsafe fn as_u8_slice(xs: &[i32]) -> &[u8] {
    std::slice::from_raw_parts(v.as_ptr() as *const u8, 
                               v.len() * std::mem::size_of::<i32>())
}

我可能会把函数写成:

fn as_u8_slice(xs: &[i32]) -> &[u8] {
    unsafe {
        std::slice::from_raw_parts(v.as_ptr() as *const u8, 
                                   v.len() * std::mem::size_of::<i32>())
    }
}

也就是说,我觉得调用函数在所有情况下都是安全的,但是编译器无法验证内部函数的作用.但是,我没有任何关于何时适合使用其中一种的规则.

That is, I feel like calling the function is safe in all cases, but what the function does internally cannot be verified by the compiler. However, I don't have any rules for when it is appropriate to use one or the other.

推荐答案

如果函数的安全性取决于其参数或全局状态,则将函数标记为 unsafe.如果函数无论参数和全局状态如何都是安全的,请不要将其标记为 unsafe.您是否认为使用 unsafe 的函数在内部安全与您是否认为 C 程序安全相同.

Mark a function as unsafe iff the function's safety depends on its parameters or on global state. If the function is safe regardless of arguments and global state, don't mark it as unsafe. Whether you consider a function that uses unsafe internally safe is the same as whether you consider a C program safe.

这篇关于如何决定何时将函数标记为不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆