我正在阅读 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/