Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Question about reference return type in C++

I write the following code:

const string& combine(string &s1,string &s2)
{
     return s1+s2;
}

but when I pass two strings to this function, the result I use "std::cout" to print is the empty string.I don’t know what the reason is.
Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The behaviour of your code is undefined. This is because s1 + s2 is an anonymous temporary and you are attempting to bind that to a reference return type.

The output you observe is a manifestation of that undefined behaviour.

Changing the return type of the function to a std::string value is a fix.

Another more interesting fix perhaps is to return one of the input strings modified, so the reference propagates back to the caller. See

#include <iostream>
#include <string>

const std::string& combine(std::string &s1, const std::string &s2)
{
     return s1 += s2;
}

int main() {
    std::string s1 = "Hello";
    std::cout << combine(s1, ", World!");
}

The introduction of const allows ", World!" to bind to s2.


In general, writing a function that returns a reference can cause unexpected issues. The C++ standard library function std::max is a well-known example: if one of the parameters is an anonymous temporary and that value is selected then you have a possibility of a dangling reference! Usually they are confined to returning class member variables (usually bound to a const reference).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading