0

Because references always “point” to valid objects, and can never be pointed to deallocated memory, references are safer to use than pointers.

Can anyone give an example of this? this doesnt make sense. couldn't you just do

int& function()
{
     int variable = 3;
     return variable&;
}

looks deallocated to me? how are they referring to references being safe?

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by vijayan121
0

> how are they referring to references being safe?

Who are 'they'?

I think they are trying to say:

void foo( A& a ) ; // we can assume that a refers to a valid object
// unless code that results in undefined behaviour has been executed 
// prior to the invocation of the function.  

void bar( A* pa ) ; // we cannot assume that pa points to a valid object
// even if code that results in undefined behaviour has never been executed 
// prior to the invocation of the function.

This would lead to undefined behaviour

int& function()
{
     int variable = 3;
     return variable&;
}

So would this:

int* pointer = new int(100) ;
int& reference = *pointer ;
delete pointer ;
reference = 7 ;

This too:

int i = 100 ;
int& r = i ;
double& reference = reinterpret_cast<double&>(r) ;
reference += 5 ;

As well as this:

int* pointer = nullptr ;
int& reference = *pointer ;
delete pointer ;
reference = 7 ;

And so forth.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.