Sign in to follow this  
Atom

C++ pointers (maintaining 3 std::vectors)

Recommended Posts

If been thinking about changing my Object Manager to pointers but I'm having an issue with deleting/nullifying a object pointer and having all the associated std::vectors follow along. I wanted to see if I could get this idea to work before actually implementing it into the actual Object Manager. For example:
// globals
std::vector<int*> all; 
std::vector<int*> u;
std::vector<int*> r;

void removeint(const int &x, bool render, bool update) {
    for(std::vector<int*>::iterator i = all.begin(); i != all.end(); ++i) {
        if((*i) != 0 && *(*i) == x) {
            delete (*i);
            (*i) = 0;

            all.erase(i);
            
            break;
        }
    }
}

void updaterender() {
    for(int i = 0; i < u.size(); ++i) {
        if(u[i] != 0)
            std::cout << "Updating: " << *u[i] << std::endl;
    }

    for(int i = 0; i < r.size(); ++i) {
        if(r[i] != 0)
            std::cout << "Rendering: " << *r[i] << std::endl;
    }

    std::cout << "all: " << all.size() << std::endl;
    std::cout << "u: " << u.size() << std::endl;
    std::cout << "r: " << r.size() << std::endl;
}

int main() {
    int x = 3; // u, r
    int y = 6; // r
    int z = 9; // u, r

    all.push_back(&x); u.push_back(&x); r.push_back(&x); 
    all.push_back(&y);                  r.push_back(&y);
    all.push_back(&z); u.push_back(&z); r.push_back(&z);

    updaterender();  // (ur1)
    removeint(x, true, true);
    updaterender();  // (ur2)
}

When I try to remove X from the all vector so that when it got to (ur2) it would crash because pointers in the u and r vectors would have been lost. So I'm guessing that each vector all, u, r each have their own pointer to X's memory location? How would I solve this so that it would crash by removing X from all and not cleaning/freeing up the u and r X memory? Thanks in advance for the help.

Share this post


Link to post
Share on other sites
This is the problem


// this is stacks variable declaration
int x = 3; // u, r
int y = 6; // r
int z = 9; // u, r

// you push its address
all.push_back(&x); u.push_back(&x); r.push_back(&x);
all.push_back(&y); r.push_back(&y);
all.push_back(&z); u.push_back(&z); r.push_back(&z);

....
....
// you try to delete it, which is not allowed.
removeint(x, true, true);
..
..





You push pointers of variables from the stacks, not from heap.
and then you try to delete the stacks, which is not correct.

EDIT: changed code tag to source

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this