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?

> 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.