Return by link

See the following code snippets. In the second function, I return the link. I declare a local variable in the function and return the address. Since the variable is local, I believe that her life ends when she leaves the function. My question is, why is it possible to access the value from the caller without any exception, even if 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

+3
source share
5 answers

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

+7
source

, .

, , , , , , , .

, - , , . .

+2

. , .

, undefined.

, .

+2

, . undefined. , , .

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

+2
source

Most likely, this will not work in these cases:

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

alternatively, in a more unpleasant way:

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

gcc will warn of errors of this type if you use -Wall

0
source

Source: https://habr.com/ru/post/1785638/


All Articles