Roman Werpachowski wrote:
In a recent thread http://tinyurl.com/8n7fe I asked about preventing
the user from deleting the object pointed to by a pointer/reference.
Now I would like to ask about a different aspect of this thing: it this
protection worth it? It is fairly obvious that deleting an object you
will need in the future is wrong. So is it worth to bother with
protecting it against deletion?
As has already been stated the return of a pointer has many problems.
The fact that they can do bad things with your internal pointer is just
one. The problem of object ownership becomes a real issue when
returning pointers - just who is going to delete the thing? What is
its lifetime? Can I depend on it to be a certain value consistently or
is it going to change the next time that function is called (for
instance C functions that returned char* often were implemented with a
static array that would get altered any time that function was
called)...
So really your issue goes beyond "just" protection from callers. I do
disagree with the other answer in that I think that alone is reason
enough to look for an alternative, but there are certainly several
other problems with returning a pointer. Obviously nothing that cannot
be worked with for programmers have been returning pointers for years,
but it just adds to the burden of coding in an unnecissary way....best
to avoid any possible problems if possible.
Had a little "argument" with a coworker about something similar today.
I prefer to keep things as safe as possible without going overboard.
Having exposed pointers is one of those things I really like to avoid
and will spend a little bit of time looking for an alternative if I
find I think I need to do that...most often I find a better way. If a
user can cause you to crash I think that is bad.
Today's argument was about a vector inside of a struct. The struct is
public and so its internal vector is as well. Things were getting
weird and an idea given to me was to make that vector a pointer. I
explained that I didn't like this idea because someone can delete it or
point it to someplace bad. Of course he "would never do that" but I
still don't like leaving that posibility open - I would then feel the
need to check that pointer any time it is accessed, at least with a
debug wrapped assert(). Now, an empty vector is no issue - I just end
up not doing anything - so the exposed vector is "ok"...but I didn't
want to do the same with a pointer....and I ended up solving the
problem in a more robust and elegant manner.
IMHO it is not silly to protect your class from users doing stupid
things - quite often that user will end up being you and the time spent
debugging may far outweigh the time looking for a method of
encapsulation.