C++ completely erase (or reset) all values of a struct?

前端 未结 3 1813
长情又很酷
长情又很酷 2020-12-25 14:37

So, I was just wondering how could we completely erase or reset a structure so it could be reused?

I just typed this up, here you go:

typedef struct          


        
相关标签:
3条回答
  • 2020-12-25 15:13

    You can just assign a constructed temporary to it:

    Part my_struct;
    
    my_struct = Part(); // reset
    

    C++11:

    my_struct = {}; // reset
    
    0 讨论(0)
  • 2020-12-25 15:15

    If for some reason I was hell-bent on keeping the same object constantly, I would just write a reset method that would reset all the values back to what they were.

    Something similar to this:

    struct Test {
        int a;
        int b;
        Test(): a(0), b(100) {}
        void reset() {
            a = 0;
            b = 100;
        }
    };
    
    int main() {
        Test test;
        //do stuff with test
        test.reset(); //reset test
    }
    
    0 讨论(0)
  • 2020-12-25 15:16

    Good practice is to avoid that type of construct (using the same variable for two different semantics meanings, having reset it in the meantime). It will inevitably create a weird bug later on when you (or somebody else) modify your code and forgets you shared a variable for two different uses.

    The only justification would be to spare some memory space but:

    • It is very unlikely that you actually need such an optimisation.
    • Even if you do, the compiler will usually figure out a variable on the stack is no longer use and can be discarded, the new variable you would create will thus effectively replace the first one. You do not need to care about sparing the memory yourself.
    • If your variables are on the heap, you are better off just using two different pointers.

    But if you really want to do this reset, you must write a method to do it. There is not built-in way in C++, because it would actually require calling the destructor and then the constructor again.

    The solution my_struct = Part() works only if your destructor is trivial. Let's say you have allocated pointer in your std::vector, you would have to properly delete every pointer before emptying the vector. That's why it cannot be done automatically: the cleanup of the structure may require special treatment rather than plain forgetting.

    0 讨论(0)
提交回复
热议问题