开发者

Return by reference

Please see the following code snippets. In the second function i am returning a reference. I am declaring a local variable in the function and is returning the address. As the variable is local I believe its life ends as it exits the function. My question is why is it possible to ac开发者_JS百科cess the value from the caller without any exceptions even though the original variable is deleted?

int& b=funcMulRef(20,3);

int* a= funcMul(20,3);


int* funcMul(int x,int y)
{
 int* MulRes = new int;
      *MulRes = (x*y);

 return MulRes;

}

int& funcMulRef(int x,int y)
{
 int MulRes ;
      MulRes = (x*y);

 return MulRes;

}

Regards, JOhn


The behaviour of the second function is simply undefined; anything can happen, and in many circumstances, it will appear to work, simply because nothing has overwritten where the result used to be stored on the stack.


You are accessing data that is no longer in scope.

The memory probably still has the data in it though so it appears to work properly but is likely to be reused at any time and the value will be overwritten.

The next time you call any function or allocate a local stack variable it's very likely to reuse that memory for the new data and overwrite what you had there before. It's underfined behavour.


The original value isn't deleted. Just because the action of deleting it will cause some unseen computations.

The value is still there, but the memory space is no longer yours, and is actually undefined.

You are pointing to a space in memory that can be overrun by the program.


No, you shouldn't do this. The result of accessing residual data on the stack is undefined. Beside that, if your return value is of class type, its destructor will have already been called.

Are you trying to avoid temporary objects? If so, you might be interested in this:
http://en.wikipedia.org/wiki/Return_value_optimization


It most likely won't work in these cases :

funcMulRef(10,3) + funcMulRef(100,500)

alternatively, in a more nasty way :

std::cout << "10*3=" << funcMulRef(10,3) << " 100*500=" << funcMulRef(100,500) << std::endl;

gcc will warn for this kind of errors if you use -Wall

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜