简体   繁体   中英

Why can't we return an object by reference from a function in C++?

What I've understood, the reason is that we unnecessarily call the copy constructor for a simple statement like a=b; (both are objects).

What I don't get is that in my book it's written that we should never pass an object by reference, because as soon as the function terminates, that reference ceases to exist.

So is the text written in my book wrong or am I missing something here? Text ref: Overloading assignment operator in C++

There's nothing wrong with returning a reference from a function.

Indeed that's how the assignment operator operator= is normally defined (with return *this; for method chaining)!

What you shouldn't do is return a reference to an object that goes out of scope, eg

int& undefinedBehaviourServer()
{
    int ub;
    return ub;
}

In this case, ub has automatic storage duration and the returned reference to it will dangle .

As soon as the function is completed, all objects declared in it are destroyed. Therefore, by returning a link from a function, you risk getting a call to a remote object. Let's see the typical example:

// don't do that!!!
std::string& get_str()
{
    std::string s = "abc";
    return s;
}


int main()
{
    string &s = get_str();
    // "abc"-string already destoyed at this moment
    std::cout << s; // attempt to deleted string: undefined behavior
}

Therefore, it is dangerous to return references to local objects from the functions, because it may involve accessing a deleted object (undefined behavior). Although technically returning an object (not local) reference is possible and often used. For example:

std::string& get_s()
{
    static std::string s = "abc";
    return s;
}
int main()
{
    std::string &s = get_s();
    std::cout << s; // that's OK
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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