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
You can just assign a constructed temporary to it:
Part my_struct;
my_struct = Part(); // reset
C++11:
my_struct = {}; // reset
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
}
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:
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.