为什么我应该完全使用参考变量? [英] Why should I use reference variables at all?

查看:82
本文介绍了为什么我应该完全使用参考变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我的第一门编程语言,我学习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

这篇关于为什么我应该完全使用参考变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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