C++:参数传递“通过引用传递"

C++: Argument Passing quot;passed by referencequot;(C++:参数传递“通过引用传递)
本文介绍了C++:参数传递“通过引用传递"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我理解与任何其他变量一样,参数的类型决定了参数与其自变量之间的交互.我的问题是,为什么要引用参数与为什么不引用的原因是什么?为什么有些函数参数引用,有些则不是?无法理解这样做的好处,有人可以解释一下吗?

I understand as with any other variable, the type of a parameter determines the interaction between the parameter and its argument. My question is that what is the reasoning behind why you would reference a parameter vs why you wouldn't? Why are some functions parameters reference and some are not? Having trouble understanding the advantages of doing so, could someone explain?

推荐答案

引用传递的能力存在有两个原因:

The ability to pass by reference exists for two reasons:

  1. 修改函数参数的值
  2. 为了避免出于性能原因复制对象

修改参数的例子

void get5and6(int *f, int *s)  // using pointers
{
    *f = 5;
    *s = 6;
}

这可以用作:

int f = 0, s = 0;
get5and6(&f,&s);     // f & s will now be 5 & 6

void get5and6(int &f, int &s)  // using references
{
    f = 5;
    s = 6;
}

这可以用作:

int f = 0, s = 0;
get5and6(f,s);     // f & s will now be 5 & 6

当我们通过引用传递时,我们传递的是变量的地址.按引用传递类似于传递指针 - 在两种情况下都只传递地址.

When we pass by reference, we pass the address of the variable. Passing by reference is similar to passing a pointer - only the address is passed in both cases.

例如:

void SaveGame(GameState& gameState)
{
    gameState.update();
    gameState.saveToFile("save.sav");
}

GameState gs;
SaveGame(gs)

void SaveGame(GameState* gameState)
{
    gameState->update();
    gameState->saveToFile("save.sav");
}

GameState gs;
SaveGame(&gs);

<小时>由于只传递地址,变量的值(对于巨大的对象可能非常大)不需要复制.因此,通过引用传递可以提高性能,尤其是在以下情况下:


Since only the address is being passed, the value of the variable (which could be really huge for huge objects) doesn't need to be copied. So passing by reference improves performance especially when:

  1. 传递给函数的对象很大(我会在这里使用指针变量,以便调用者知道函数可能会修改变量的值)
  2. 该函数可以被多次调用(例如在循环中)

另外,阅读 const 参考资料.使用时不能在函数中修改参数.

Also, read on const references. When it's used, the argument cannot be modified in the function.

这篇关于C++:参数传递“通过引用传递"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why does C++ compilation take so long?(为什么 C++ 编译需要这么长时间?)
Why is my program slow when looping over exactly 8192 elements?(为什么我的程序在循环 8192 个元素时很慢?)
C++ performance challenge: integer to std::string conversion(C++ 性能挑战:整数到 std::string 的转换)
Fast textfile reading in c++(在 C++ 中快速读取文本文件)
Is it better to use std::memcpy() or std::copy() in terms to performance?(就性能而言,使用 std::memcpy() 或 std::copy() 更好吗?)
Does the C++ standard mandate poor performance for iostreams, or am I just dealing with a poor implementation?(C++ 标准是否要求 iostreams 性能不佳,或者我只是在处理一个糟糕的实现?)