Using memset on structures in C++

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.


Yes, that would work. However, I don't think malloc is necessarily bad practice, and I wouldn't change it just to change it. Of course, you should make sure you always match the allocation mechanisms properly (new->delete, malloc->free, etc.).

You could also add a constructor to the struct and use that to initialize the fields.

Tags:

C++

Memset

Memcmp