One problem for returning a reference to a constant would be if the user encoded something like:
const std::string & str = myObject.getSomeString() ;
When std::string returned, the temporary object will remain alive and bound to str until str leaves the scope.
But what happens to const std::string & ? I assume that we will have a const reference to an object that can die when its parent object releases it:
MyObject * myObject = new MyObject("My String") ; const std::string & str = myObject->getSomeString() ; delete myObject ;
So, I prefer returning the const link (because, in any case, I'm just more comfortable sending the link than hoping the compiler will optimize the extra temporary) if the following contract is followed: "if you want it to be above my existence object, they copy it until the destruction of my object "
paercebal Sep 25 '08 at 20:58 2008-09-25 20:58
source share