Re: fails to call destructor in a linked list
On 2013-02-26 13:35, alexo wrote:
// insert an element to the top of the list
void push(Node **phead, int value)
{
Node *n = new Node(value);
if(n != 0)
{
[...]
}
else
cout << "\nmemory allocation error." << endl;
}
// pushes an element to the end of the list
void pushBack(Node **phead, int value)
{
Node *temp = new Node(value);
if(temp != 0)
{
[...]
}
else
{
cout << "memory allocation error.";
}
}
I haven't seen anyone point this out so far, so let me add this:
The default 'new' doesn't "return" NULL but throws a std::bad_alloc
exception, so there's no point in checking the "returned" value
against NULL (because once it "returns," the value can never be NULL).
(Quotes on the words "return" because the 'new' expression is
technically not a function call, though it involves one to the
'operator new' function.)
For a simple program like this, you can just rely on the fact that
once a memory allocation error occurs, an exception will prevent the
program flow from going further and abort the program, and not worry
about error handling at all. For a more sophisticated program, you'll
need to write an exception handler by using try/catch, not an if.
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]