I have these three helper functions that I've used on some projects as a slightly better alternative to the C memset
function. The objective is to simplify and clarify code, as well as add assert
s where possible:
// Zero fills a POD type, such as a structure or union.
template<class T>
void ZeroStruct(T & s)
{
std::memset(&s, 0, sizeof(T));
}
// Zero fills a statically allocated array of POD or built-in types. Array length inferred by the compiler.
template<class T, size_t N>
void ZeroArray(T (&arr)[N])
{
std::memset(arr, 0, sizeof(T) * N);
}
// Zero fills an array of POD or built-in types, with array length provided by the caller.
template<class T>
void ZeroArray(T * arr, size_t arrayLength)
{
assert(arr != nullptr);
assert(arrayLength != 0);
std::memset(arr, 0, sizeof(T) * arrayLength);
}
Usage example:
int arr[128];
ZeroArray(arr);
struct S {
int x;
float y;
};
S s;
ZeroStruct(s);
I'd like to further improve those functions with C++11/14 features. I think it would be a good idea to static_assert
with std::is_pod
to ensure they are never called on a class instance. Do you agree?
Also, should I make them noexept
?
Any other recommendations?