简体   繁体   English

在C ++函数中通过引用返回的目的是什么?

[英]What is the purpose of returning by reference in C++ functions?

My question is about returning by reference in a function. 我的问题是关于在函数中通过引用返回。 For example , I have the code: 例如,我有代码:

main.cpp main.cpp中

class Vector{
public:
    Vector(int a , int b){
        x = a;
        y= b;
    }

    Vector() { }

    int x = 1;
    int y = 1;
};

Vector& operator+(const Vector& lvec ,const Vector& rvec ){
    Vector resvec;
    resvec.x = lvec.x + rvec.x;
    resvec.y = lvec.y + rvec.y;
    return resvec;
}

int main(){
    Vector vecone(1,2);
    Vector vectwo(1,2);
    Vector resultvec = vecone + vectwo;
    cout<<endl<<"X:"<<resultvec.x<<endl<<"Y:"<<resultvec.y;
}

It runs and works very well, however , I don't seem to understand the purpose of the reference operator ( & ) in the operator overloading function , yet i've seen it in many source code's containing operator overloading functions. 它运行并运行良好,但是,我似乎不理解运算符重载函数中引用运算符(&)的用途,但我在许多源代码中都看到它包含运算符重载函数。 The program seems to run very well when I dismiss the operator, so my question is - what's the purpose of returning by reference in a funcion? 当我解雇运算符时程序似乎运行得很好,所以我的问题是 - 在函数中通过引用返回的目的是什么? and does it serve a special objective in the code I presented? 它在我提供的代码中是否有特殊目的?

This definition of the operator 这个运营商的定义

Vector& operator+(const Vector& lvec ,const Vector& rvec ){
Vector resvec;
resvec.x = lvec.x + rvec.x;
resvec.y = lvec.y + rvec.y;
return resvec;
}

is wrong. 是错的。 It returns a reference to local object resvec that will be destroyed after the control will exit the function. 它返回对本地对象resvec的引用,该引用将在控件退出函数后被销毁。 So the reference will be invalid and as result the program has undefined behaviour. 因此引用将无效,因此程序具有未定义的行为。

A correct definition can look like 正确的定义可能看起来像

Vector operator +( const Vector& lvec , const Vector& rvec )
{
    return { lvec.x + rvec.x, lvec.y + rvec.y };
}

Or like 或者喜欢

Vector operator +( const Vector& lvec , const Vector& rvec )
{
    return Vector( lvec.x + rvec.x, lvec.y + rvec.y );
}

Or returned type can be declared like const Vector 或者返回的类型可以像const Vector一样声明

Nevertheless a reference as the return type is used very often especially in the declaration of the subscript operator 然而,作为返回类型的引用经常被使用,尤其是在下标运算符的声明中

Consider for example 例如,考虑一下

Here is a demonstrative program 这是一个示范计划

#include <iostream>

class Vector
{
public:
    Vector( int a , int b ) : x( a ), y( b )
    {
    }

    Vector() : x( 0 ), y( 0 )
    { 
    }

    size_t size() const { return 2; }

    int & operator []( size_t i ) { return i == 0 ? x : y; }
    int operator []( size_t i ) const { return i == 0 ? x : y; }

private:
    int x;
    int y;
};

int main() 
{
    Vector v( 10, 20 );

    for ( size_t i = 0; i < v.size(); i++ ) std::cout << v[i] << ' ';
    std::cout << std::endl;

    for ( size_t i = 0; i < v.size(); i++ ) ++v[i];

    for ( size_t i = 0; i < v.size(); i++ ) std::cout << v[i] << ' ';
    std::cout << std::endl;
}

Its output is 它的输出是

10 20 
11 21 

The point is that operator+ must be overloaded in a way that is proper to its functionality according to the language syntax. 关键是必须根据语言语法以适合其功能的方式重载operator+

When you have (a + b) + c the subexpression (a + b) should return a temporary value which is then added to c . 当你有(a + b) + c ,子表达式(a + b)应返回一个临时值,然后将其添加到c So returning a reference makes no sense since a + b should generate a new value which is distinguished from others. 因此返回引用是没有意义的,因为a + b应该生成一个与其他值不同的新值。

Indeed you could return a reference to 实际上你可以返回一个引用

  • an existing object, which is semantically wrong since it means you are mutating something when + binary operator shouldn't. 一个现有的对象,它在语义上是错误的,因为它意味着当+二元运算符不应该改变某些东西时。
  • a temporary object, but returning a reference to a temporary object will leave you just a dangling reference (and that's your case) 一个临时对象,但是返回对临时对象的引用会让你只是一个悬空引用(这就是你的情况)

That's why usually operator+ should return a T , not a T& . 这就是为什么operator+应该返回T而不是T& The situation is the opposite with operators like operator+= or operator++ which indeed mutate the state of the object are called on, so returning a reference is the right choice in that situation. 这种情况与operator operator+=operator++这样的operator+=相反,它确实调用了对象的状态,因此在这种情况下返回引用是正确的选择。

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

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