sarathy said:
Hi,
I have been using C++ for a while. I am not entirely clear with
the concepts of reference in C++.
- Why was there a need for introducing a concept called "Reference" in
C++ when everything was working fine with normal pointers?
It wasn't fine, was it? Pointers *are* tricky. Now, in C++ the trickyness of
pointers is compounded by exceptions: since exceptions can divert the flow
of control at almost any point and toward unknown locations, the basic
requirement of a pointer that every new() is matched by a delete() along
each path of execution is harder to match. Thus, a device was created to
eliminate some uses of pointers. References and standard containers are in
this category. Other devices, like auto_ptr, were introduced to mitigate
the dangers for the remaining cases of pointer use.
- Is there anything that a reference can do that a pointer cannot ???
References can extend the life-time of temporaries:
#include <iostream>
struct log {
log ( void ) {
std::cout << "construction" << std::endl;
}
log ( log const & ) {
std::cout << "copy" << std::endl;
}
~log ( void ) {
std::cout << "destruction" << std::endl;
}
void access ( void ) const {
std::cout << "access" << std::endl;
}
};
log create_tmp ( void ) {
return ( log() );
}
int main ( void ) {
{
log const & ref = create_tmp();
ref.access();
}
std::cout << std::endl;
{
// warning: UB
log const * ptr = &create_tmp();
ptr->access();
}
}
// end of file
Best
Kai-Uwe Bux