c++ - 关于通过引用传递参数的说明

标签 c++ reference

在阅读将引用作为参数传递给函数时,我发现了这篇文章 passing arguments by reference (以及它所讨论的代码)在某一点上说:

void getSinCos(double degrees, double &sinOut, double &cosOut)
{
   //SOME PROCESSING WITH THE PARAMETERS
}

The caller must pass in arguments to hold the updated outputs even if it doesn’t intend to use them. More importantly, the syntax is a bit unnatural, with both the input and output parameters being put together in the function call. It’s not obvious from the caller’s end that sin and cos are out parameters and will be changed. This is probably the most dangerous part of this method (as it can lead to mistakes being made). Some programmers and companies feel this is a big enough problem to advise not passing by reference this way, and using pass by address instead when mixing in and out parameters (which has a clearer syntax indicating whether a parameter is modifiable or not).

当定义的参数是非常量引用时,我们当然不能传递像参数 3 或其他一些整数/双文字这样的临时变量,但是如何修改输入变量和恢复在同一个变量中输出(因为对原始变量进行了更改)会像本文指出的那样很麻烦吗?有人可以指导我吗,因为我是 C++ 的新手。

最佳答案

这是人们可能根本想不到的事情。假设你有这样的代码:

int x = 5;
foobar(x);

函数调用后 x 的值是多少?大多数人会期望它仍然是 5,因为除非有未定义的行为,否则它在按值传递时不会更改。在 C 中甚至没有通过引用传递,所以值总是 5。现在在 C++ 中,突然出现了引用传递,仅从那段代码,您无法知道函数调用后 x 是否会发生变化。为此,您必须查看 foobar 的实际签名。

它本身并不“危险”,但如果使用不当,可能会导致代码不清晰和误导。特别是如果您混合使用参数,有些是输出参数,有些不是,还有一些具有误导性的名称。在您的示例中,参数名称包含 out 以指示它们是 out 参数,这是减轻这种危险的好风格。

将此与以下代码段进行对比 from here解释引用传递在 C# 中的作用:

void Method(ref int refArgument)
{
    refArgument = refArgument + 44;
}

int number = 1;
Method(ref number);
Console.WriteLine(number);
// Output: 45

在这里您可以立即看到它是通过引用传递的,因为它显示了 ref number

关于c++ - 关于通过引用传递参数的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54212898/

相关文章:

c++ - const 引用和返回值

android - dlopen 失败 : cannot locate symbol "__cxa_finalize" referenced by "/system/lib/libdl.so"

c++ - 如何从 boost::thread 取回值?

c++ - 有没有办法按值搜索宏名称?

php - &$PHP 中的变量

objective-c - 保留和复制之间的区别?

c++ - 在里面。静态成员,而 COPY CTOR 是私有(private)的

c++ - 是否允许标准库算法复制谓词参数?

c++ - 如何防止相机 vector 中的浮点错误

c# - 通过 ref 将函数传递给委托(delegate)有区别吗?