问题描述
作为我学习的第一门编程语言,我学习了 Java,但自从我换了另一所大学,我现在正在学习 C++.
As my first programming language I learned Java, but since I changed to a different University, I am now learning C++.
来自 Java 并学习 C++ 的基础知识,我阅读了关于引用和引用变量的内容.以及它们有多危险,以及如何小心对待它们等等.
Coming from Java and learning the basics of C++, I read about references and reference variables. And how dangerous they can be, and how to be careful with them and so on.
所以我的脑海中出现了一个简单的问题:为什么我要费心使用那种复杂的,因此可能会导致问题的东西?
So in my head arises one simple question: Why should I bother using that kind of complicated, and therefore potentially problem-causing, stuff at all?
它是否值得,还是只是 RAM 大约 64MB 大的时代的遗物?
Is it somehow worth it, or just a relic from times where RAM was about 64MB big?
由于很多答案都提到了指针:这个概念显然来自石器时代,恕我直言.除了高性能计算,我什至不会碰那些东西.
Since a lot of answers have mentioned pointers: That concept is clearly from the stone age, imho. Except for high-performance-computation I wouldn't even touch that stuff.
推荐答案
问题与引用本身无关.
问题在于,在 C++ 中,对象生命周期的管理方式与 Java 或其他使用垃圾收集器的运行时环境不同.C++ 没有标准的内置垃圾收集器.C++ 对象生命周期可以是自动的(在本地或全局范围内)或手动(在堆中显式分配/释放).
The problem is that in C++, object lifetime is managed differently than in Java or other run-time environments that use a garbage collector. C++ doesn't have standard built-in garbage collector. C++ object lifetime can be automatic (within local or global scope) or manual (explicitly allocated/deallocated in heap).
C++ 引用只是对象的简单别名.它对对象生命周期一无所知(为了效率).程序员必须关心它.一个例外是引用绑定到临时对象的特殊情况;在这种情况下,临时对象的生命周期延长到绑定引用的生命周期.详情在此处.
A C++ reference is just a simple alias for an object. It doesn't know anything about object lifetime (for the sake of efficiency). The programmer must care about it. An exception is the special case where a reference is bound to a temporary object; in this case, the lifetime of the temporary is extended to lifetime of the bound reference. Details are here.
参考是 C++ 基本概念的重要组成部分,您无法避免在 90% 的任务中使用它们.否则你必须使用指针,这通常更糟:-)
References are an important part of C++ basic concepts and you just cannot avoid using them for 90% of tasks. Otherwise you have to use pointers, which is usually even worse :-)
例如,当您需要将对象作为函数参数通过引用而不是通过值传递时,您可以使用引用:
E.g., when you need to pass object as function argument by reference instead of by value you can use references:
void f(A copyOfObj); // Passed by value, f receives copy of passed A instance
void f(A& refToObj); // Passed by ref, f receives passed A instance itself, modifiable
void f(const A& refToObj); // Passed by const ref, f receives passed A instance itself, non modifiable
这篇关于为什么我应该使用引用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!