Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with returning arguments that are const references

I know why the following does not work correclty, so I am not asking why. But I am feeling bad about it is that it seems to me that it is a very big programming hindrance.

#include <iostream>
#include <string>
using namespace std;

string ss("hello");

const string& fun(const string& s) {
        return s;
}

int main(){
        const string& s = fun("hello");
        cout<<s<<endl;
        cout<<fun("hello")<<endl;
}

The first cout will not work. the second cout will.

My concern is the following:

Is it not possible to imagine a situation where a method implementor wants to return an argument that is a const reference and is unavoidable?
I think it is perfectly possible.
What would you do in C++ in this situation?

Thanks.

like image 963
user855 Avatar asked Apr 12 '26 03:04

user855


1 Answers

In C++, it is important to establish the lifetimes of objects. One common technique is to decide upon an "owner" for each object. The owner is responsible for ensuring that the object exists as long as it is needed, and deleting it when not needed.

Often, the owner is another object that holds the owned object in an instance variable. The other typical ways to deal with this are to make it a global, a static member of a class, a local variable, or use a reference-counted pointer.

In your example, there is no clear ownership of the string object. It is not owned by the main() function, because it is not a local variable, and there is no other owner.

like image 183
Kristopher Johnson Avatar answered Apr 14 '26 21:04

Kristopher Johnson