Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 837
user2117427 Avatar asked Mar 03 '13 07:03

user2117427


People also ask

How do you clear a struct 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.

Can struct have default value?

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 .


2 Answers

You can just assign a constructed temporary to it:

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

C++11:

my_struct = {}; // reset 
like image 182
Pubby Avatar answered Sep 16 '22 17:09

Pubby


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 } 
like image 27
Rapptz Avatar answered Sep 18 '22 17:09

Rapptz