使用box关键字和Box :: new有什么区别? [英] What is the difference between using the box keyword and Box::new?

查看:261
本文介绍了使用box关键字和Box :: new有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

box只是语法糖,还是可以用于Box::new不够用的用例?我在某个地方读到box不稳定,这是否意味着我只能在每晚的Rust版本中使用它?

Is box just syntactic sugar or can it be applied to use cases where Box::new is not sufficient? I read somewhere that box is unstable, does that mean I can only use it with the nightly Rust versions?

推荐答案

Box::new只是一个函数,与其他任何函数一样.它在任何方面都不是特别的.它很烂,闻起来很接近到期日期奶酪.

Box::new is just a function, like any other function. It is not special in any way whatsoever. It is grubby and smells faintly of very-close-to-the-expiration date cheese.

box是魔法,由地面小精灵和小孩的梦组成.它穿着最好,最时髦的衣服,并带有刚切下的松木的淡淡香气.

box is magic and made up ground-up pixies and the dreams of little children. It is dressed in the finest, swankiest clothes and carries with it the faint aroma of freshly cut pine.

当执行Box::new(e)时,由于它是一个函数,因此必须在 开始之前完全评估和构造e.如果这意味着在堆栈上分配并填充500kB结构,那么它必须在堆栈上分配并填充500kB结构,然后然后将其传递给Box::new,只有 /em>可以分配堆上的空间(这可能会失败),然后 将该500kB复制到堆中.

When you execute Box::new(e), because it is a function, e must be completely evaluated and constructed before it can start the call. If this means allocating and filling a 500kB structure on the stack, then it has to allocate and fill a 500kB structure on the stack, and then pass that to Box::new, which only then can allocate the space on the heap (which might fail), and then copy that 500kB into the heap.

当执行box e时,由于它就像在炎热的夏日下凉风一样美妙,因此编译器可以通过在堆上分配500kB 重新排序开始 >然后直接在堆上填充500kB结构 .然后完成.无需额外的复制,也无需仔细检查堆栈空间.如果分配在堆上"的事情解决不了,那就不要浪费精力.

When you execute box e, because it is wonderful like a cool breeze on a hot summer's day, the compiler can reorder things such that it begins by allocating the 500kB on the heap, and then filling the 500kB structure directly on the heap. And then it's done. No extra copying, no chewing through stack space. No wasted effort if that "allocate on the heap" thing fails to work out.

box是生命,box是爱;全部冰雹box

box is life, box is love; all hail box!

(是的,在撰写本文时,它仍然很不稳定,这意味着您需要使用每晚编译器来散发出光芒.但是很快,黎明就要来了.明白了吗?黎明?每晚? ..我将展示自己...)

(And yes, as of writing, it's still unstable which means you need a nightly compiler to bask in its radiance. But soon, the dawn will come. Get it? Dawn? Nightly? ... I'll show myself out...)

这篇关于使用box关键字和Box :: new有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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