指针和引用之间的真正区别是什么? [英] What is the real difference between Pointers and References?

查看:28
本文介绍了指针和引用之间的真正区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

又名 - 对指针的痴迷是什么?

AKA - What's this obsession with pointers?

我只真正使用过现代的、面向对象的语言,如 ActionScript、Java 和 C#,我不太了解指针的重要性以及您使用它们的目的.我在这里错过了什么?

Having only really used modern, object oriented languages like ActionScript, Java and C#, I don't really understand the importance of pointers and what you use them for. What am I missing out on here?

推荐答案

这一切都只是间接的:不处理数据的能力,而是说我会引导你到那边的一些数据".您在 Java 和 C# 中有相同的概念,但只是参考格式.

It's all just indirection: The ability to not deal with data, but say "I'll direct you to some data, over there". You have the same concept in Java and C#, but only in reference format.

主要区别在于引用实际上是不可变的路标——它们总是指向某些东西.这很有用且易于理解,但不如 C 指针模型灵活.C 指针是您可以愉快地重写的路标.您知道您要查找的字符串位于所指字符串的隔壁吗?好吧,稍微改变一下路标.

The key differences are that references are effectively immutable signposts - they always point to something. This is useful, and easy to understand, but less flexible than the C pointer model. C pointers are signposts that you can happily rewrite. You know that the string you're looking for is next door to the string being pointed at? Well, just slightly alter the signpost.

这与 C 的接近骨干,需要低级知识"方法结合得很好.我们知道 char* foo 由一组从 foo 路标指向的位置开始的字符组成.如果我们也知道字符串至少有 10 个字符长,我们可以将路标更改为 (foo + 5) 以指向相同的字符串,但从一半的长度开始.

This couples well with C's "close to the bone, low level knowledge required" approach. We know that a char* foo consists of a set of characters beginning at the location pointed to by the foo signpost. If we also know that the string is at least 10 characters long, we can change the signpost to (foo + 5) to point at then same string, but start half the length in.

这种灵活性在您知道自己在做什么时很有用,如果不知道就会死亡(知道"不仅仅是知道语言",而是知道程序的确切状态").弄错了,你的路标会指引你离开悬崖边缘.引用不会让您摆弄,因此您更有信心可以毫无风险地遵循它们(尤其是在与被引用的对象永远不会消失"这样的规则结合使用时,就像在大多数垃圾收集语言中一样).

This flexibility is useful when you know what you're doing, and death if you don't (where "know" is more than just "know the language", it's "know the exact state of the program"). Get it wrong, and your signpost is directing you off the edge of a cliff. References don't let you fiddle, so you're much more confident that you can follow them without risk (especially when coupled with rules like "A referenced object will never disappear", as in most Garbage collected languages).

这篇关于指针和引用之间的真正区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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