HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Wrapper template functions for memset()

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
templatewrapperforfunctionsmemset

Problem

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 asserts where possible:

// Zero fills a POD type, such as a structure or union.
template
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
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
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?

Solution

Don't do that it is so easy to have incorrect usage.

All your cases can be done using normal syntax in C++.

// int arr[128];
// ZeroArray(arr);

int arr[128] = {0}; // Zero whole array.
// Or better yet use a vector.
std:vector  arr(128); // zero init the vector of 128 elements.
// Or alternatively an array
std::array arr(0);

// S s;
// ZeroStruct(s);
S s = S();          // Calls the default constructor for zero initialization.


See:

C++ implicit copy constructor for a class that contains other objects

Proper way to initialize C++ structs

Does a c++ struct have a default constructor?

Code Snippets

// int arr[128];
// ZeroArray(arr);

int arr[128] = {0}; // Zero whole array.
// Or better yet use a vector.
std:vector<int>  arr(128); // zero init the vector of 128 elements.
// Or alternatively an array
std::array<int,128> arr(0);

// S s;
// ZeroStruct(s);
S s = S();          // Calls the default constructor for zero initialization.

Context

StackExchange Code Review Q#64432, answer score: 3

Revisions (0)

No revisions yet.