为什么“动"?在 Rust 中实际上没有移动? [英] Why does "move" in Rust not actually move?

查看:37
本文介绍了为什么“动"?在 Rust 中实际上没有移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子中:

struct Foo {
    a: [u64; 100000],
}

fn foo(mut f: Foo) -> Foo {
    f.a[0] = 99999;
    f.a[1] = 99999;
    println!("{:?}", &mut f as *mut Foo);

    for i in 0..f.a[0] {
        f.a[i as usize] = 21444;
    }

    return f;
}
fn main(){
    let mut f = Foo {
        a:[0;100000]
    };

    println!("{:?}", &mut f as *mut Foo);
    f = foo(f);
    println!("{:?}", &mut f as *mut Foo);
}

我发现在传入函数foo之前和之后,f的地址是不一样的.为什么 Rust 到处复制这么大的结构体,却没有真正移动它(或实现这种优化)?

I find that before and after passing into the function foo, the address of f is different. Why does Rust copy such a big struct everywhere but not actually move it (or achieve this optimization)?

我了解堆栈内存的工作原理.但是通过 Rust 中的所有权提供的信息,我认为可以避免复制.编译器不必要地复制数组两次.这是对 Rust 编译器的优化吗?

I understand how stack memory works. But with the information provided by ownership in Rust, I think the copy can be avoided. The compiler unnecessarily copies the array twice. Can this be an optimization for the Rust compiler?

推荐答案

移动是一个 memcpy,然后将源视为不存在.

A move is a memcpy followed by treating the source as non-existent.

你的大数组在堆栈上.这就是 Rust 的内存模型的工作方式:局部变量在堆栈上.由于 foo 的堆栈空间在函数返回时会消失,因此编译器除了将内存复制到 main 的堆栈空间外,别无他法.

Your big array is on the stack. That's just the way Rust's memory model works: local variables are on the stack. Since the stack space of foo is going away when the function returns, there's nothing else the compiler can do except copy the memory to main's stack space.

在某些情况下,编译器可以重新排列事物,以便可以省略移动(源和目标合并为一个事物),但这是不能依赖的优化,尤其是对于大事物.

In some cases, the compiler can rearrange things so that the move can be elided (source and destination are merged into one thing), but this is an optimization that cannot be relied on, especially for big things.

如果您不想复制庞大的数组,请自己在堆上分配它,或者通过 Box<[u64]>,或者简单地使用 Vec<;u64>.

If you don't want to copy the huge array around, allocate it on the heap yourself, either via a Box<[u64]>, or simply by using Vec<u64>.

这篇关于为什么“动"?在 Rust 中实际上没有移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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