I heard a saying that c++ programmers should avoid memset,
class ArrInit {
//! int a[1024] = { 0 };
int a[1024];
public:
ArrInit() { memset(a, 0, 1024 * sizeof(int)); }
};
so considering the code above,if you do not use memset,how could you make a[1..1024] filled with zero?Whats wrong with memset in C++?
thanks.
Description. The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.
For one thing, sizeof(my_array) returns the total number of bytes in the data structure and not the number of elements. Also, your code would've just copied the pointer. You need to actually copy the data it points to since the target is not pointers--it's actual structures.
Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values. The reason is simple, memset works byte by byte.
You can assume that memset will be at least as fast as a naive implementation such as the loop. Try it under a debug build and you will notice that the loop is not replaced. That said, it depends on what the compiler does for you. Looking at the disassembly is always a good way to know exactly what is going on.
In C++ std::fill
or std::fill_n
may be a better choice, because it is generic and therefore can operate on objects as well as PODs. However, memset
operates on a raw sequence of bytes, and should therefore never be used to initialize non-PODs. Regardless, optimized implementations of std::fill
may internally use specialization to call memset
if the type is a POD.
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