Cheers...
What does your favourite C++ book say about them, and what don't
you understand there? Have you tried reading the FAQ on this
topic?
Doesn't point 6 show how references can be "dangling" ?
> 3. pointers can be changed to point to other object, references not.
> 4. while passing parameters through pointers, copies of pointers are
> made , 4 byte for each pointer on 32bit system, and while passing
> parameters through refrences, compiler can optimize further and even
> can save the 4 byte copy operation.
> 5. In previous case, while using pointer , you have to use & operator,
> and using references, you save one key typing time.
> 6. When u will combine pointer and references, u can have a situtation
> like this
> int *p = new int;
> int & q =*p;
> ......
> int *r = &q;
> delete r; ///somewhere in program
> .........
> q = 20; ///what is happening here?
>
7. It is an error not to initialize a reference to a valid object.
8. References can increase the lifetime of a temporary to the lifetime
of the reference, pointers can not (see below).
#include <iostream>
#include <ostream>
struct A
{
A()
{
std::cout << "A default\n";
}
A( const A & )
{
std::cout << "A copy\n";
}
A & operator= ( const A & )
{
std::cout << "A operator =\n";
return * this;
}
~A()
{
std::cout << "A Destruct\n";
}
};
int main()
{
{
const A & a = A();
std::cout << "Temporary lives !\n";
A y( a );
}
std::cout << "Temporary is gone !\n";
{
const A * a = & A();
std::cout << "Temporary is gone already - a dangles!\n";
}
}