Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why or why not use memset in C++? [closed]

I have a lot of memset in a program which I have to maintain. Is it a good practice in modern C++ to use memset?

Why and why not?

If not, what should be preferred to memset?

like image 266
kiriloff Avatar asked Oct 04 '14 18:10

kiriloff


1 Answers

90% of the time you should use std::fill instead of memset. This is because std::fill will work correctly with classes, and it will also work when setting arrays of non-byte types to a non-zero value. For example, you can memset an array of ints to 0 but you can't memset an array of ints to 0x12345678. With std::fill you can.

Good compilers can optimize std::fill to a memset where suitable. In the cases they don't, any performance impact is likely to be negligible.

Using std::fill when a memset would be faster isn't dangerous. Using memset where std::fill should have been used is dangerous. Default to std::fill.

Ditto for memcpy and std::copy

like image 107
Neil Kirk Avatar answered Oct 12 '22 22:10

Neil Kirk