James Roseman
James Roseman

Reputation: 1624

Class Self-Reference Issues

All of my code can be found here.

I'm trying to create a complicated tree for a project however this is just the beginning of the project (the construction of a data structure). Also, I think it would help to know that the data structure can be anything you want, and that I really want to do it this way. If you think another is better, that's grand, but I don't want to change my data structure if I don't have to, as I'd like to follow this idea through.

That said, I'm creating a tree.

Each node of the tree contains a string of content, bool of if it is a non-terminal (if it has children or if it is a leaf).

Additionally, each node contains a pointer to a vector (let's call that vector v).

V is such that it contains other vectors. Let's call one of those vectors X.

X contains a pointer to a node.

The code works fine except for when X contains a pointer to the node which contains V (if that makes sense). When X contains a pointer to the node which contains V, I get an infinite loop which terminates in a seg fault.

I've been hashing this out for an hour and am pretty sure the problem is in my deconstructor, which looks like this:

Node :: ~Node () {
    for (int i = 0; i < (*children).size(); i++) {
        for (int j = 0; j < (*children)[i].size(); j++) {
            if ((*children)[i][j] != selfP) {
                delete (*children)[i][j];
            }
        }
    }
}

What I want to do is something like this:

for (int i = 0; i < (*children).size(); i++) {
    for (int j = 0; j < (*children)[i].size(); j++) {
        if ((*children)[i][j] != CURRENT_NODE_ADDRESS) {
            delete (*children)[i][j];
        }
    }
}

But I can't quite figure out how to reference the address of a class I'm currently defining. Any thoughts?

Upvotes: 1

Views: 1392

Answers (2)

Nasser Ghazali
Nasser Ghazali

Reputation: 21

maybe you can easily compare your object with 'this' :

if (children[i][j] == this)
{
...
}

where children[i][j] is a pointer to an instance of the class that you are writing deconstructor.

Upvotes: 2

smhx
smhx

Reputation: 2266

have you tried the this pointer?

Upvotes: 2

Related Questions