开发者

unintentional recursive call in destructor

I have created a class which includes a linked list and this class needs to have a destructor for deleting the linked list, which I have included however because the delete method itself calls the destructor I end up in an infinite recursive call situaction.

Here is the code:-

PolynomialNode::~PolynomialNode()
{
    /*PolynomialNode* current_node_ptr = link;
    PolynomialNode* header_ptr = link;
    int index = 0;
    if( link != NULL)
    {
        while( current_node_ptr != NULL)
        {
            index++;
            current_node_ptr = current_node_ptr->get_link();

        }

        delete_nodes( &header_ptr, 0, index);
    } */
    PolynomialNode* current_node_ptr = link;
    PolynomialNode* copy_ptr;
    while( current_node_ptr != NULL)

    {
        copy_ptr = current_node_ptr->get_link();
        current_node_ptr->set_link(NULL);
        d开发者_运维技巧elete current_node_ptr;
        current_node_ptr = copy_ptr;
    }
}

Note I tried this with a recursive call - intentional for deleting the linked list and I still have the same problem.

Any help would be much appreciated.

NB: I know it's a recursive call because when I step through the debugger I can see it happening.


assuming link is the pointer to the next PolynomialNode, simply

PolynomialNode::~PolynomialNode()
{
    delete link;
}

will do the right thing recursively.

However, a better solution might be to retain your while() loop but move it out of the node to the destructor of a separate class representing the linked list as a whole.


Add this line in the while loop, before delete:

if ( current_node_ptr == this ) continue;

This will allow you to avoid recursion, by skipping destruction of the node that is calling. However, you should ask yourself why the heck did this happen in the first place. I cannot answer that question, because I don't see the rest of the code.

Note: this is wrong unless you have a circular link, in case of which this would be a valid design, as long as you skip deleting this.


Assuming link is the pointer to the next PolynomialNode, simply

if(this->link != NULL) delete this->link;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜