- Oct 10, 2006
- 21,562
- 3
- 0
Originally posted by: irishScott
^^^^^^^
ie:
char* asdf;
Calling delete on such an item produces run-time errors up the arse.![]()
Originally posted by: programmer
Yeah, get into the practice of always assigning values to pointers at declaration, including null. In C++ this is perfectly legal:
char* foo = 0; // or null or NULL
delete foo; // no problem
No problem there, but leaving it undefined will most definitely crash:
char* foo;
delete foo; // BOOM because foo is pointing to some random memory address
delete foo; // no problem
Originally posted by: iCyborg
There's no need to check for NULL when deleting:
http://www.parashift.com/c++-f...ore-mgmt.html#faq-16.8
Yes, it's a compiler thing and there might be some old and obscure one that would do something bad.
Originally posted by: iCyborg
Not sure what you mean. Since it's effectively a no-op, it's never needed explicitly. But it's not uncommon that one doesn't know whether a pointer is null or not when deleting it.
And I like it this way, many people do "if (p!=null) delete p;", but I've never seen "else throw..."
Originally posted by: Markbnj
Well, you would see "else throw..." if the pointer should not be null at that point in the program execution. If the programmer doesn't know whether the pointer is null, as you suggest, then there's no reason to throw an exception. Obviously either state is acceptable.
I'll have to go back and look at some of my old code and see how often I used that "if (p) delete p;" pattern. By old I mean > 10 years. I've been using structured exception handling for so long that the pattern looks cumbersome to me now. Why would a pointer be null when you delete it? The allocation failed, the allocation was never performed, the object was deleted somewhere else?
The most common case I see is a large class with a default constructor. For the reasons from the OP, the member pointers are set to null in the initializer list. And in the destructor I guess it's mostly just a safeguard to check for null, as the user might not have called functions that had set them to something, or they failed.