fl <
rxj...@gmail.com> wrote:
> "because the value of a pointer
> is distinct from the value of the object to which it points."
I suppose that what the author is trying to say is that when you assign
a pointer to another, they will both point to the same object, rather
than the object itself being copied as well.
This raises a problem of ownership, and dangling pointers.
The most common problematic scenario is if you allocate something
dynamically (with 'new') and then have two pointers pointing to it.
Since C++ doesn't natively offer any automation on how to manage
the lifetime of that dynamically allocated object, you need to either
be extremely careful with how you handle those pointers, or use
exclusively something like std::shared_ptr to handle it. (In general
it's advisable to avoid this situation altogether, if you can.)
But that's only one scenario that causes a problem. You don't even
need dynamic allocation to encounter problems. Suppose you have
something like this:
class C
{
int table[10];
int* tablePtr;
public:
C(): tablePtr(&table[0]) {}
};
That 'tablePtr' is supposed to point to an element of 'table'.
But consider what happens if you do this:
C obj1;
C obj2 = obj1;
Where do you think the tablePtr of obj2 is pointing to?
This becomes especially dangerous if you do seemingly innocuous
things like:
C foo() { return C(); }