what happens when the function returning value is a pointer and the returning type is a reference in c++?

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-06 14:04:03

问题


guys, I just got a bonus question from my teacher! Thanks for helping me !!

The sub2 below does not result in a run-time error, but there may be some other problem. What is the problem?

enter code here

int& sub2 ( int& a , int& b ){
int * pc = new int ;
*pc = a - b ;
return (*pc ) ;
}

回答1:


This function MIGHT lead to memory leaks.

  • If the user of this function just relies on the signature of the function, he'll assume that the function returns a reference to an object that someone else owns. Hence the object that was allocated will not be released.

  • Of course, if the user is aware of the trick, he could still delete the object by taking the address of the reference

  • If the function is used in a larger expression (which is quite tempting, given the signature), such as sub(3, sub(2,1)) he will not get the opportunity to catch the temporary reference.

Note that this function MIGHT also throw a bad_alloc if there's an issue with the memory allocation.



来源:https://stackoverflow.com/questions/29316665/what-happens-when-the-function-returning-value-is-a-pointer-and-the-returning-ty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!