pointers - 在 Rust 中返回指针时发生了什么?

标签 pointers rust

我正在阅读 return pointers part防 rust 指南。 这是它的示例代码:

struct BigStruct {
    one: int,
    two: int,
    // etc
    one_hundred: int,
}

fn foo(x: Box<BigStruct>) -> BigStruct {
    return *x;
}

fn main() {
    let x = box BigStruct {
        one: 1,
        two: 2,
        one_hundred: 100,
    };

    let y = box foo(x);
}

以下解释的重要部分让我感到困惑:

There is no copy in this code. main allocates enough room for the `box , passes a pointer to that memory into foo as x, and then foo writes the value straight into that pointer. This writes the return value directly into the allocated box.

已阅读 a related question , 我还是没明白 no-copy 点。

函数 foo 是否返回 *x 的副本? 如果是,如何理解解释? 如果不是,是否与所有权和借款有关?

我理解所有权和借用的概念,只是不知道什么时候发生。

最佳答案

指南试图告诉您代码的行为就好像它是这样写的:

struct BigStruct {
    one: int,
    two: int,
    // etc
    one_hundred: int,
}

fn foo(x: Box<BigStruct>, result: &mut BigStruct) {
    *result = *x;
}

fn main() {
    let x = box BigStruct {
        one: 1,
        two: 2,
        one_hundred: 100,
    };

    unsafe {
        let mut y = box std::mem::uninitialized();
        foo(x, &mut *y);
    }
}

main 创建一个 Box 并将指向框内部的指针作为输入参数传递给 foo。这样,foo 可以直接将结果值存储在那里,而不是返回它并让 main 将它复制到框中。

foo 中发生了复制(从第一个框到第二个框),但是如果 foo 没有直接写入框,就会有两个副本(可能是从第一个盒子到 foo 中的堆栈,然后从堆栈到 main 中的第二个盒子)。

P.S.:我认为指南中有错误。它说:

passes a pointer to that memory into foo as x

但是 x 是我们试图从中复制的框,而不是新框...相反,它传递一个指针作为隐藏参数。

关于pointers - 在 Rust 中返回指针时发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25840109/

相关文章:

rust - 以原子方式更新多个线程之间重叠的向量或切片的正确方法是什么?

c++ - 如何使用迭代器?

c++ - C++中的动态树

c++ - 对我的 BFS tile 类中的引用和指针感到困惑

while-loop - 在while循环中 panic ,而不是在满足条件时停止

rust - Clippy提示严格的f32比较

将复杂类型指针复制到 C 中的另一个指针

C语言 : How is swapping pointers different from swapping the value pointed to?

rust - 如何在 read_to_string 更改为占用缓冲区后创建链接 API?

c - Rust 中使用 C FFI 的代码如何与 header 保持同步?