开发者

returning referece of a local string object

string& GetMyStr(string& somestr)
{
   string & str=somestr;
   //do something with str
   return str;
}

str is a local obj开发者_如何学Pythonect, but why I can still get the value after return ? I think right after the function return, it too is gone and the return value is not referenced. I think I miss it, maybe.


Because you're returning a reference to the argument which exists outside the function. You're taking the argument by reference as somestr and then making str refer to that object, so str is not a local object, but a reference to the object that the caller passes to the function.

This creates a reference to the argument passed in:

string & str=somestr;

Then you return it as a reference. Any operations you do to str in the meanwhile are done to somestr so the caller's argument is modified.

You'll see that if you print the argument you pass to GetMyStr and then print the return value of that call that the strings are the same (or you could just compare the addresses which will also be the same).


somestr is a reference, and so refers to an object that's outside GetMyStr's scope. As such, it will still exist after GetMyStr returns, allowing you to safely use it. This would have been much different if somestr was not a reference, because then you would have returned a reference to a copy of the object (a local variable).


str is a local object

No, it isn't. The type of str is string&, so it is a reference. In particular, it refers to the somestr that was passed in by reference; that is, to the caller's string. That will obviously still exist after the function returns.


I think I asked a simillar question in the below mentioned thread. You could take a look at this. It became clear to me after a few mins! :) ( although I am discussing about pointers, there is nothing else to get confused about :D)

Pointer - returning Local reference in C++

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜