Problem with temporary

Possible duplicate:
return type in C ++

#include<iostream>
int& fun();
int main()
{
  int p=fun();
  std::cout<<p;
  return 0;
}

int & fun()
{
  int a=10;
  return  &a;
}

why this code gives an error as, error: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'.. In fact, I do not quite understand the time points, i.e. when they are created and when they are destroyed. Also, explain, to some extent, temporary.

+3
source share
6 answers

&a creates a temporary one that cannot be bound to a non-constant link.

In addition, your code has several drawbacks.

1) &ahas a type int*, whereas you are returned via the ie link int &. Types do not match.

2) &a a , , , - UB.


++ .

, -

int &x = 5; 

int(5) , . const ,

const int &x = 5;

const- . , x .

+8
#include<iostream> 

int& fun(); 
int main() 
{   
    int p=fun();  
    std::cout<<p;  
    return 0; 
}  

int & fun() 
{   
   int a=10;   
   return  a; //Return a not &a
}

invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'' is because you are returning & a and not a`. , . . , , - . , .

!

:

#include<iostream> 

int* fun(); 
int main() 
{   
    int *p =fun();  
    std::cout<< *p;  
    delete p; //delete dynamically allocated memory else memory leak
    return 0; 
}  

int* fun() 
{   
   int *a = new int;  //allocate dynamic memory 
   *a = 10;
   return  a; 
}
+1

&a fun, a fun.

new malloc ( delete free ), , fun. , (, int foo), .

0

a , , .

0

, &a " a". , int; .

a new, delete , undefined.

0

int&. foo of &a (address-of) int*. int&, *&a. , , a, , . . ( ) undefined ( : . : ).

In this case, you basically have 2 options: change the signature of your function to int foo()or change the local declaration in ahow static int a, and the return statement to return a;. Please note that changing aas static will make the function non-cost-effective and non-threadafe.

0
source

All Articles