Reverse changes to int after DMA

Say I have the following variable initialized within a class:

class testClass {
public:
    int someInt = 5;
};

and I want to add to or modify it using like this:

int main() {
    testClass *t = new testClass;
    cout << t->someInt << endl;
    t->someInt = 1;
    cout << t->someInt << endl;
    delete t;
    cout << t->someInt;
}

How can I revert the changes done by the t->someInt to someInt back to the initial declaration, of int i = 5?

Also, when I call delete before cout << t->someInt still exists. Why does the output of t->someInt still equals 1? Shouldn't it have been deleted?

I am working on a game where it has present variables and I want to dynamically change the variables, such as a score, when the player gets a point to release memory and allow the player to replay the game after the variables are reverted back.

3 answers

  • answered 2018-07-10 21:34 johnyak

    In order for "t" to not have a value, you have to set it to nullptr. (t = nullptr)

  • answered 2018-07-10 21:54 J. Calleja

    How can I revert the changes done by the t->someInt to someInt back to the initial declaration, of int i = 5?

    You have to store a copy of the values you want to revert. You can either store just the int or a copy of the whole class.

    For example, the following code stores the current value of t inside t_backup:

    int main()
    {
        testClass *t = new testClass;
        cout << t->someInt << endl;
    
        testClass *t_backup = new testClass(*t);
    
        t->someInt = 1;
        cout << t->someInt << endl;
    
        *t = *t_backup;
        cout << t->someInt << endl;
    
        delete t_backup;
        delete t;
    }
    

    Obviously, if your class is more complex, you will have to define your own copy constructor and assignation operator.

    Also, when I call delete before cout << t->someInt still exists. Why does the output of t->someInt still equals 1? Shouldn't it have been deleted?

    After you call delete, any use of the variable is "undefined behaviour". It means that (almost) anything can happen. It can print a number or it can crash your computer.

  • answered 2018-07-10 22:09 Jerry Coffin

    There are a couple of approaches.

    The first and simplest is to just make a copy of the variable (or more than one). Based on what you've said, this is probably what you really want.

    int input1 = 1;
    char input2 = 'a';
    
    while (play_game(input1, input2))
        ;
    

    This repeatedly calls play_game, and each time it does, the two variables will start out with the prescribed values. play_game can modify its local copies of them as it sees fit, but as soon as it exits, those changes disappear.

    If you really do get into a situation where you need to modify an object, and later return that object to its previous value, you might want to consider the memento pattern.