问题
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