声明未初始化变量的更好方法

声明未初始化变量的更好方法

本文介绍了声明未初始化变量的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些libc函数,例如 sigemptyset(set: *mut sigset_t) 获取指针变量,将其视为未初始化并初始化.

Some libc functions, e.g. sigemptyset(set: *mut sigset_t) take a pointer to a variable, treat it as uninitialized and initialize it.

我最终得到以下代码:

let mut newmask = std::mem::uninitialized();
libc::sigemptyset(&mut newmask);

这没关系,但是当我拥有许多这些变量时,最终得到的是这样的东西:

This is ok, but when I have many of those variables I end up with something like this:

let mut newmask = std::mem::uninitialized();
let mut oldmask = std::mem::uninitialized();
let mut pendmask = std::mem::uninitialized();

我可以浓缩一下:

use std::mem::unitialized as uninit;
let (mut newmask, mut oldmask, mut pendmask) = (uninit(), uninit(), uninit());

有没有更好的方法来编写此代码?出于教育目的,我明确希望使用libc.

Is there a nicer way to write this code? For educational purposes I explicitly want to use libc.

推荐答案

幸运的是,元组也是普通类型.那么:

Luckily, tuples are normal types, too. So how about:

let (mut newmask, mut oldmask, mut pendmask) = std::mem::uninitialized();

但是,没有比这更好的了.最好的选择是将所有变量组合成更大的类型(例如元组或结构),然后将其取消初始化.

However, it won't get much nicer than this. Your best bet is to combine all your variables into a bigger type (like a tuple or a struct) and un-initialize that.

但是,不安全的东西冗长而烦人是可以的.未初始化的变量确实非常危险,尤其是在处理Drop类型时.我确定您已经知道了,但是我仍然要确保每个人都阅读 uninitialized() 的文档以了解所有可能的陷阱.

But it's fine that unsafe things are verbose and annoying to write. Uninitialized variables are really quite dangerous, especially when dealing with Drop types. I am sure you are already aware, but I still want to make sure everyone reads the documentation of uninitialized() to understand all possible pitfalls.

这篇关于声明未初始化变量的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:41