简体   繁体   English

C ++函数返回/输入参考类型

[英]C++ Function Return/Input Reference Type

I'm way too confused of reference return/input types. 我对参考返回/输入类型感到困惑。 I think I can best ask my question by explaining my understanding. 我想我最好通过解释我的理解来问我的问题。

When a reference is input to a function as an argument as below... 当一个引用作为参数输入函数时,如下所示......

void squareByReference( int & );

int main ()
{
    int z = 4;
    sequareByReferece( z );

    return 0;
}

int squareByReference( int &numberRef )
{
   numberRef *= numberRef;
}

I understand it as in the 'squareByReference,' &numberRef is received by the function as an address to an int variable, but 'somehow' can be recognized and treated just like a normal int variable. 我理解为'squareByReference',并且函数接收numberRef作为int变量的地址,但是'somehow'可以像普通的int变量一样被识别和处理。 Therefore, the line 'numberRef *= numberRef; 因此,行'numberRef * = numberRef; can treat numberRef as a normal int even though it's actually an address. 可以将numberRef视为普通的int,即使它实际上是一个地址。

I'm okay with this. 我没关系。 I get it and no problem interpreting/coding programs. 我明白了,解释/编码程序没问题。

However, when it comes down to reference return, it makes me confused too much. 然而,当它归结为参考回归时,它让我感到困惑。

int g_test = 0;

int& getNumberReference()
{
    return g_test;
}

int main()
{
    int& n = getNumberReference();

    n = 10;
    std::cout << g_test << std::endl; // prints 10
    std::cout << getNumberReference() + 5 << std::endl; // prints 15

    return 0;
}

My confusion is this: Why is 'n' defined as a reference int variable?! 我的困惑是:为什么'n'被定义为变量的引用?! Following my previous logic, the getNumberReference() returns a reference variable, and even though it is actually an address to an int, it should be 'somehow' treated as equal to normal int variable. 按照我之前的逻辑,getNumberReference()返回一个引用变量,即使它实际上是一个int的地址,它应该“某种程度上”被视为等于普通的int变量。 Therefore, it should be saved in int variable not reference to int variable! 因此,它应该保存在int变量中而不是引用int变量! This logic works perfectly fine when it comes to the line 'std::cout << getNumberReference() + 5 << std::endl;.' 当涉及到行'std :: cout << getNumberReference()+ 5 << std :: endl;。'时,这个逻辑非常正常。 It is 'somehow' treated as a normal int variable and prints 15. 它以某种方式被视为普通的int变量并打印15。

Could you please correct my understanding to resolve my question on int& definition??? 请你纠正我的理解来解决关于int和定义的问题???

When you are talking about references, you have to differentiate between syntax and semantics. 在谈论引用时,必须区分语法和语义。 The syntax for references - once they are initialized/bound to an object - is almost the same as for normal variables. 引用的语法 - 一旦初始化/绑定到对象 - 几乎与正常变量相同。 Their semantic however is more similar to pointers and - as far as function parameters and return types are concerned - are typically implemented in exactly the same way. 然而,它们的语义更类似于指针,并且 - 就函数参数和返回类型而言 - 通常以完全相同的方式实现。

Function Parameters 功能参数
Passing a reference as a function parameter means that every time you access that variable, you actually access the original object, the same way as you would if you'd pass a pointer and dereference it. 将引用作为函数参数传递意味着每次访问该变量时,实际上都会访问原始对象,就像传递指针并取消引用它一样。 Now inside a function you will usually see no difference between pass by value or pass by reference, as (in single threaded code) you are the only one to change the contents of that variable anyway and so it doesn't matter for you whether you are working on the actual object or a copy. 现在在函数内部,您通常会看到传递值或按引用传递没有区别,因为(在单线程代码中)您是唯一一个无论如何都要更改该变量的内容,因此对您而言无关紧要正在研究实际的对象或副本。 One situation, where this is no longer true is if the parameter aliase each other: 一种情况,即不再是这样的情况是参数是否相互混淆:

void foo(int& a, int& b) {
    a=1;
    std::cout << b << std::endl;
}  
int main() {
    int p=2;
    foo (p,p); //this will print 1 instead of 2;
}

And of course it does always matter outside the function, because with pass-by-references you changed the original object outside the function and with pass-by-value you only changed a local copy. 当然,它在函数外部总是很重要,因为通过引用传递,您更改了函数外部的原始对象,并且通过值传递,您只更改了本地副本。

Function return values 函数返回值
Nothing prevents you from writing: 没有什么能阻止你写作:

int n = getNumberReference();

in which case the returned reference would be treated as a "normal int variable", so n would end up to be a copy of that object and you would print 0 and 5 instead. 在这种情况下,返回的引用将被视为“正常的int变量”,因此n最终将成为该对象的副本,而您将打印0和5。
What you are doing, however, is to create a new reference and bind it to whatever getNumberReference() returns. 但是,您正在做的是创建一个新引用并将其绑定到getNumberReference()返回的任何内容。 If getNumberReference would return a plain int, your program would run into undefined behavior, as you are referencing a temporary variable that doesn't exist past the semicolon anymore. 如果getNumberReference将返回一个纯int,那么您的程序将遇到未定义的行为,因为您正在引用一个不再存在分号的临时变量。 However, your code is returning a reference instead and n is not bound to the returned reference itself, but to the object that reference references in the first place (like copying a pointer). 但是,您的代码返回引用而n并未绑定到返回的引用本身,而是绑定到首先引用引用的对象(如复制指针)。 As it so happens, that object is a global object, whose lifetime exceeds anything inside main , so n can be used safely after the semicolon. 碰巧的是,该对象是一个全局对象,其生命周期超过main任何内容,因此n可以在分号后安全使用。 As a result, n and g_value are now two names representing the same object in memory and whenever you change that object via one of its names, you can observe that change via the other. 因此, ng_value现在是两个代表内存中同一对象的名称,每当您通过其中一个名称更改该对象时,您可以通过另一个名称观察到该更改。 Thats why it is usually bad practice, if multiple (non-const) identifiers in one scope aliase the same object. 这就是为什么通常不好的做法,如果一个范围内的多个(非const)标识符别名同一个对象。

To sum that up, in most cases it is better to think of references as syntactic sugar for pointers instead of normal variables. 总而言之,在大多数情况下,最好将引用视为指针的语法糖而不是正常变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM