Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning value by reference in C++

Tags:

c++

I was doing my homework assignment and encountered a question which required us to return a value by reference. I got the question correct, but I'm not sure why. Can anyone care to explain me how this member function of a struct actually works. (or you could even direct me to a detailed resource). The code for the member function is:

double& SafePtrToDouble::Dereference(){
  if((*this).d!=nullptr){ 
    return *((*this).d);
  }
  else{ throw std::logic_error("Error");}
}

Please tell if this description is a little vague. Thank you!

like image 479
Esh200111 Avatar asked Nov 29 '25 06:11

Esh200111


2 Answers

When returning a value by reference problems might arrise when a the memory of the returned referenced object is freed. This might happen for example because the object has automatic lifetime and the variable goes out of scope and is freed. Since the value is returned by reference this would result in a dangling reference. In your case the lifetime of the referenced object does not have auto lifetime. Therefore the returned refernce stays valid after the function call and no dangling refernce triggers undefined behaviour.

Example of a typical error:

double& SafePtrToDouble::Dereference(){
    double retval= 10;
    return retval; //the address of retval is returned
} // the variable retval is freed => reference is dangling now
like image 71
David Feurle Avatar answered Dec 01 '25 19:12

David Feurle


double is a distinct type to double &, but they are related. You need a double object somewhere to initialise a double & value. Reference types are one of the two kinds of types that aren't objects.

In this case, the expression *((*this).d) identifies the object that the reference binds to. You can think of a reference variable as a new name for an existing object. An object with dynamic storage duration ("on the heap") doesn't have a name when it is created, so a reference could be the "only" name it has.

like image 44
Caleth Avatar answered Dec 01 '25 20:12

Caleth