Using memset for structures in C ++

Hey guys. I am working on fixing old code for my work. It is currently written in C ++. They converted the static distribution to dynamic, but did not edit memsets / memcmp / memcpy. This is my first programming internship, so hungry with my new question, somehow.

The following code is in C, but I want to have it in C ++ (I read that malloc is not good practice in C ++). I have two scenarios: first, we created f. Then you use & f to fill with zero. The second is the * pf pointer. I am not sure how to set pf for all 0, as in the previous C ++ example.

Can you just do pf = new foo instead of malloc and then call memset(pf, 0, sizeof(foo)) ?

 struct foo { ... } f; memset( &f, 0, sizeof(f) ); //or struct foo { ... } *pf; pf = (struct foo*) malloc( sizeof(*pf) ); memset( pf, 0, sizeof(*pf) ); 
+6
c ++ memset memcmp
source share
4 answers

Yes, but only if foo is a POD. If he received virtual functions or something else remotely with C ++ ish, do not use memset on it, as it will stomp on all the internal elements of the structure / class.

What you probably want to do, rather than memset, is let foo the constructor explicitly initialize its elements.

If you want to use a new one, do not forget to delete the corresponding one. It would be even better to use shared_ptr :)

+8
source share

You can? Yes it is possible. You should? Not.

While it probably works, you are losing the state that the constructor built for you. Adding to this, what happens when you decide to implement a subclass of this structure? Then you lose the advantage of the reusable code that C ++ OOP offers.

Instead, you should create a constructor that initializes the members for you. That way, when you create this structure later in the line, you simply use this constructor to help you subclass. This is a free, secure code! use it!

Edit: The caveat is that if you already have a huge code base, do not modify it until you begin to subclass the structures. It works like it does now.

+3
source share

Yes, that will work. However, I don't think malloc is bad practice, and I would not change it to change it. Of course, you must make sure that you always match the distribution mechanisms correctly (new-> delete, malloc-> free, etc.).

You can also add a constructor to the structure and use it to initialize the fields.

+2
source share

You can create a new foo (as a standard way in C ++) and implement a constructor that initializes foo, rather than using memset.

eg.

 struct Something { Something() : m_nInt( 5 ) { } int m_nInt; }; 

Also, do not forget if you use the new one to call delete when you are done with the object, otherwise you will end the memory leak.

+2
source share

All Articles