I am working on fixing older code for my job. It is currently written in C++. They converted static allocation to dynamic but didn't edit the memsets/memcmp/memcpy. This is my first programming internship so bare with my newbe-like question.
The following code is in C, but I want to have it in C++ ( I read that malloc isn't good practice in C++). I have two scenarios: First, we have f created. Then you use &f in order to fill with zero. The second is a pointer *pf. I'm not sure how to set pf to all 0's like the previous example in C++.
Could 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) );
The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.
Most certainly, memset will be much faster than that loop. Note how you treat one character at a time, but those functions are so optimized that set several bytes at a time, even using, when available, MMX and SSE instructions.
No overhead of memory freed is there for the programmer in the memset function as it does not allocate any memory which needs to be freed explicitly.
Note: We can use memset() to set all values as 0 or -1 for integral data types also.
Yes, but only if foo is a POD. If it's got virtual functions or anything else remotely C++ish, don't use memset on it since it'll stomp all over the internals of the struct/class.
What you probably want to do instead of memset is give foo a constructor to explicitly initialise its members.
If you want to use new, don't forget the corresponding delete. Even better would be to use shared_ptr :)
Can you? Yes, probably. Should you? No.
While it will probably work, you're losing the state that the constructor has built for you. Adding to this, what happens when you decide to implement a subclass of this struct? Then you lose the advantage of reuseable code that C++ OOP offers.
What you ought to do instead is create a constructor that initializes the members for you. This way, when you sublass this struct later on down the line, you just use this constructor to aid you in constructing the subclasses. This is free, safe code! use it!
Edit: The caveat to this is that if you have a huge code base already, don't change it until you start subclassing the structs. It works as it is now.
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