saneman said:
I have written C++ code for some time now using both pointers and
references.
I was asked what the point was in using pointers and could not give a
short an explanatory example.
I would say that you use a pointer when data are updated across function
calls.
But does anyone have an idea to a minimal example where its impossible
to avoid pointer?
You can have a vector of pointers, but not a vector of references.
As a particular case of the "reseating" issue already noted by Erik,
consider a class that may (according to your design philosophy) have a
member either a reference member or a pointer member. If the target
object of the pointer or reference (the referee?) is not yet available
when the referring (pointy?) object is constructed, then a reference is
out of the question. Code like the following even flags a compile-time
error from g++:
struct S {
S() { }
void set_i(int*);
private:
int& i_;
};
g++ -ansi -pedantic -Wall -c -o main.o main.cc
main.cc: In constructor 'S::S()':
main.cc:2: error: uninitialized reference member 'S::i_'
make: *** [main.o] Error 1
A pointer, by contrast, can be temporarily initialized to a reasonable
default value, and later assigned a more permanent value.
A pointer is an object in its own right, with its very own address in
memory. A reference is just a way of referring to an existing object,
and may or may not require run-time support from pointer-like entities.
You can have a reference to a pointer, but not a reference to a reference.