I am trying to reset an array of simple objects to zero, as shown below:
using Node = std::array<std::uint16_t, 256>;
using Array = std::array<Node, 4096>;
void reset_1(Array& a) {
std::fill(std::begin(a), std::end(a), Node{});
}
void reset_2(Array& a) {
a = {};
}
void reset_3(Array& a) {
a.fill(Node{});
}
All these functions get the job done, but looking at the compiler explorer (using both Clang 10.0.1 and gcc 10.2), reset_2
does it in one memset
, while the other two do it in multiple chunks (same result using std::fill_n
).
In my real case, I actually want to reset all nodes, except for the first one. This would lead me to write something like:
void reset_not_zero_1(Array& a) {
std::fill(std::begin(a) + 1, std::end(a), Node{});
}
void reset_not_zero_2(Array& a) {
std::memset(a.data() + 1, 0, sizeof(a) - sizeof(Node));
}
My question is: am I invoking some sort of undefined behavior with reset_not_zero_2
? The array is trivially copyable, but maybe I am missing something.
No. Seems fine to me.