Topic: C++ Programming Standards
Author: David R Tribble <david.tribble@central.beasys.com>
Date: 1997/12/16 Raw View
References: <EL5y1y.7A2@world.std.com>
Rolf F. Katzenberger wrote:
> Well, let's hope that at least _some_ programmers set unused
> pointers to NULL, so testing for NULL makes sense...
Mark Wilden <Mark@mWilden.com> responded:
> I don't hope that. I think automatically setting pointers to 0 is a
> mistake, unless there has been a conscious design decision to do so
> in certain cases. Otherwise, it's just a way to hide bugs, rather
> than uncover and fix them.
Steven W McDougall responded:
> I have code that throws exceptions.
> It can be very difficult to keep track of whether pointers (file
> handles, sockets, etc) have been allocated when the stack unwinds.
> So I set them to 0 in the constructor, allocate them as necessary,
> reset them to 0 after they are deleted, and and delete them
> unconditionally in the destructor. I also assert() them on function
> entry.
> It works for me...
Exactly. Leaving pointers to deleted objects unchanged is simply
courting disaster. Once you delete an object, you've created a
dangling pointer (by definition). Setting the dangling pointer
to NULL fixes it, changing it from a dangling pointer into a
well-defined pointer.
Exceptions, signals, and longjmp() all increase the possibility
of code executing in nonlinear order. All of these things
could be out of your control, too, if they are present in the third
party libraries that your application binds to. All of these
things are reasons for keeping memory leaks, dangling pointers,
unclosed resources, and the like to a minimum. Also, a second
delete of a dangling pointer is undefined behavior; deleting a
NULL pointer is benign.
Not resetting an out-of-date pointer to NULL is just bad
programming. Preserving dangling pointers doesn't hide bugs,
it creates them.
In a related vein, constructors should initialize ALL of the
object members to reasonable initial values. This means, in
particular, initializing member pointers to NULL.
-- David R. Tribble, david.tribble@noSPAM.central.beasys.com --
---
[ comp.std.c++ is moderated. To submit articles: Try just posting with your
newsreader. If that fails, use mailto:std-c++@ncar.ucar.edu
comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
Comments? mailto:std-c++-request@ncar.ucar.edu
]
Author: lump@vulcan.inlink.com (Dan Jost)
Date: 20 Jan 1995 01:46:32 GMT Raw View
Hello
I am looking for some programming standards/guidelines to help me define
our own guidelines at my company. If anyone can help me out please email me
at lump@inlink.com or just post here. Thanks
Dan Jost