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 PART_STRUCT { unsigned int Id; std::string Label; } Part; typedef struct OBJECT_STRUCT { std::vector< unsigned char > DBA; std::vector< Part > Parts; unsigned int Id; } Object; Object Engine; // Initialize all members of Engine // Do whatever with Engine // ... // Erase/Reset Engine value
The easiest solution is to write a method which does a reset of all the individual members. In C, we use memset(&struct_var, 0, sizeof(struct whatever)) when we know for sure that 0 or NULL is an acceptable initial value for all of its members.
For variables of class types and other reference types, this default value is null . However, since structs are value types that cannot be null , the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null .
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With