"reference" 的概念在 C++ 和 Rust 中是否不同?

Is the concept of "reference" different in C++ and Rust?

C++ 代码

#include <iostream>
#include <string>
using namespace std;

int main() {

string food = "Burger";

cout << &food << endl;

return 0;

}

用 Rust 编写的相同代码:

fn main() {
    let food = "Burger";

    prinln!("{}", &food);
}

C++ 程序的输出:

0x7fff604b2890

Rust 程序的输出:

Burger

为什么会这样?我错过了什么?

首先,在 C++ 中 & (address-of) operator return 是一个 指针 ,即给定 T t;&t会 return 一个 T*.

C++ 确实有引用 (T&),它们 不是 通过 & 运算符创建的,我将指向您 this great answer for numerous differences between C pointers and C++ references.

现在回答你的问题,引用的概念在 C++ 和 Rust 之间是完全不同的

Rust 的引用本质上是智能指针。如果我们从上面的 link 列表向下看,Rust 引用:

  • 可以初始化unset
  • 可以是re-bound
  • 有自己的标识(大小、在内存中的位置……)
  • 可以嵌套
  • 可以取消引用
  • 可以放入其他东西

它们也是使用 & 运算符创建的,它们都是指针属性。

虽然它们是指针,但它们不是 C 指针,它们是“智能”的,因为它们是(类型)安全的,因此像 C++ 引用一样不能 null 或悬空.但这使它们成为 safe/sane 指针。总的来说,它们仍然经常充当指针。

至于你遗漏了什么,答案是 Display (the trait used to format things) is blanket-implemented on references by delegating to the parent object,所以当你打印“a reference”时,它会打印所引用的任何内容,因为......这更有用,特别是考虑到Rust 中的引用有多常见(它们非常非常常见)[0].

如果你想要引用的“指针值”,你可以使用the pointer value formatting specifier(感谢trentcl):

println!("{:p}", &food);

(您也可以转换为原始指针,这是我最初编写的内容,但如果您只想打印该值,则需要做更多的工作才能获得很少的回报)。

[0] 公平地说,其他 Rust 智能指针的行为相同:BoxRc,并且朋友们都将 Display 委托给基础类型