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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With