简体   繁体   English

返回对int的引用与在c ++函数中返回int?

[英]returning a reference to an int vs returning an int in c++ function?

int& returnC() {
    return c;
}

So part of my question has been answered by another question here but I'm still a bit confused. 因此,我的部分问题已在此处被另一个问题回答,但我仍然有些困惑。 So I know this returns a reference not an address. 所以我知道这将返回引用而不是地址。 But what's the advantage of this definition, you're just returning c why not define it as: 但是此定义的优势是什么,您只是返回c而不将其定义为:

int returnC() {
    return c;
}

what's the advantage of returning an reference to an int and not just an int if they both return the same variable? 如果它们都返回相同的变量,则返回对int而不是int的引用有什么好处?

what happens if I declare it like this: 如果我这样声明,会发生什么:

int& returnC() {
    return &c;
}

Thank you! 谢谢!

Return by value 按价值回报

Return by value is the simplest and safest return type to use. 按值返回是最简单,最安全的返回类型。 When a value is returned by value, a copy of that value is returned to the caller. 当按值返回值时,该值的副本将返回给调用方。 Eg: 例如:

int returnC() {
    return c;
}

Return by reference 参考退货

Just like with pass by reference, values returned by reference must be variables (you can not return a reference to a literal or an expression). 就像通过引用传递一样,通过引用返回的值必须是变量(您不能返回对文字或表达式的引用)。 When a variable is returned by reference, a reference to the variable is passed back to the caller. 通过引用返回变量时,对该变量的引用将传递回调用方。 The caller can then use this reference to continue modifying the variable, which can be useful at times. 然后,调用者可以使用该引用来继续修改变量,这有时会很有用。 Return by reference is also fast, which can be useful when returning structs and classes. 按引用返回也很快,这在返回结构和类时很有用。 Eg: 例如:

// This struct holds an array of 25 integers
struct MyArrays
{
    int ArrValue[25];
};


// Returns a reference to the nIndex element of rArray
int& Value(MyArrays &rArray, int nIndex)
{
    return rArray.ArrValue[nIndex];
}

int main()
{
    MyArrays objArray;

    // Set the 10th element of objArray to the value 5
    Value(objArray, 10) = 5;

    cout << objArray.ArrValue[10] << endl;
    return 0;
}

With the first version: 对于第一个版本:

int returnC() {
    return c;
}

You are just returning a copy of c. 您只是返回c的副本。 The caller can do whatever they want with this copy and it will never affect s 调用者可以使用此副本执行任何操作,并且永远不会影响s

with the second version (no need to take address of c): 使用第二个版本(无需使用c的地址):

int& returnC() {
    return c;
}

The caller would be able to write 呼叫者将能够写

returnC() = 5

and set the member c to 5. I'm assuming c is a data member of a class since I don't see it defined anywhere. 并将成员c设置为5。我假设c是类的数据成员,因为我在任何地方都看不到它的定义。 If c isn't a data member of a class then you would be returning a reference to a temporary which wont exist when the caller of returnC tries to use it and should be avoided 如果c不是类的数据成员,那么您将返回对一个临时引用,该临时引用在returnC的调用者尝试使用它时将不存在,应避免使用

To return an int I would probably use return by value. 要返回一个整数,我可能会使用按值返回。 Unless I wanted the caller to be able to change c, but this leaks implementation details and is generally considered bad practise. 除非我希望调用者能够更改c,否则这会泄漏实现细节,通常被认为是不好的做法。 If I wanted to return an object I might do this by const reference. 如果我想返回一个对象,可以通过const引用来实现。 This saves copying the class without giving the caller the ability to alter the object. 这样就节省了复制类的时间,而没有使调用者能够更改对象。 If the caller needed to alter the object then we would be back to returning by value 如果调用者需要更改对象,那么我们将返回按值返回

It depends on where is your variable declared. 这取决于您的变量在哪里声明。 You only can return a reference if the variable has not automatic storage inside the function. 如果变量在函数内部没有自动存储,则只能返回引用。 I mean, you never have to do something like this: 我的意思是, 您无需执行以下操作:

int& foo () {
     int a = 1;
     return a;
}

In this case, a is variable with automatic storage. 在这种情况下, a是自动存储的变量。 When function returns, the variable is lost and you have a reference to a destroyed variable, which is a very bad thing. 当函数返回时,该变量将丢失,并且您具有对已销毁变量的引用,这是一件很糟糕的事情。

If you have a member variable of a class or a global one, you can return it by value or by reference. 如果您有一个类的成员变量或全局变量,则可以按值或引用返回它。 The difference is then of semantics: if you return by value, only its value is important and variable will be copied. 区别在于语义:如果按值返回,则仅其value很重要,并且变量将被复制。

On the other hand, by returning a reference you allowed to modify the original data. 另一方面,通过返回引用,您可以修改原始数据。 It could be faster since no copy is required. 由于不需要复制,因此可能会更快。 But it is a different thing. 但这是另一回事。

class MyClass {
     int a;

public:
     int& foo () { return a; }
     int foo () { return a; }
     /* ... */
};

The class MyClass has an int member a . 类MyClass有一个int成员a You can return a by value or by reference. 您可以按值或引用返回a The difference here is the meaning. 这里的区别是含义。 Are you allowing to modify the original data? 是否允许修改原始数据? If so, return by reference. 如果是这样,请参考返回。

Your last example is wrong: 您的最后一个示例是错误的:

int& returnC() {
    return &c;
}

Your function says: "I am returning a reference to int", but return &c means you are returning a pointer to it. 您的函数说:“我正在返回对int的引用”,但是return &c表示您正在返回指向它的指针。 In that case the correct way is: 在这种情况下,正确的方法是:

int* returnC() {
    return &c;
}

Then you are returning a pointer to int and you must not return a pointer to a automatic variable either. 然后,您将返回一个指向int的指针,也不得返回一个指向自动变量的指针。

It may look like returning a reference to an int is the same as returning an int, but in fact they are two fundamentally different things. 看起来返回一个int的引用与返回一个int相同,但是实际上它们是两个根本不同的事情。

Return By Reference 引用返回
When you return a reference to an Object/primitive (such as an int), you are returning a reference to the variable being returned in your method. 当您返回对对象/基元(例如int)的引用时,您将返回对方法中返回的变量的引用。 For objects, this is advantageous since the object doesn't have to be copied and rather just a reference to that object just be returned. 对于对象,这是有利的,因为不必复制对象,而只需返回对该对象的引用即可。
It also allows you to do this: 它还允许您执行以下操作:

int& max(int &x, int &y){
    if (x > y){
        return x;
    }

    return y;
}

int main(){
    int x = 10, y = 12;

    //This sets, y to 0.
    max(x, y) = 0;
}


Return By Value 按价值回报
When you return an Object/primitive itself (again, such as an int), you are returning a copy of the variable and not the actual variable itself. 当您返回对象/基元本身(同样,例如int)时,您将返回变量的副本 ,而不是实际变量本身。 This doesn't matter as much for primitive types such as int or char but for objects, this can be a lot slower . 对于基本类型(例如intchar ,这无关紧要,但是对于对象而言,这可能要慢得多 Simply put, a copy of the object that is being returned has to be created with that object having the exact same values for attributes. 简而言之,必须创建要返回的对象的副本 ,并使该对象的属性值完全相同。

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

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