I have this code
char * oldname = new char[strlen(name) + 1];
memcpy(oldname,name,strlen(name) + 1);
name = new char[strlen(oldname) + strlen(r.name) + 1];
memset(name, '\0', strlen(name));
strcat(name,oldname);
strcat(name," ");
strcat(name,r.name);
I understand that it is a no no to use memcpy and memset but I haven't understood exactly how to use this in C++, preferably without std.
Does anyone know? Thank you.
In general, there's std::fill
. http://www.cplusplus.com/reference/algorithm/fill/
Or in this particular instance, you should consider using std::vector<char>
.
(Note that memset
can still be used in C++ if you use #include <cstring>
, although it's less idiomatic in C++.)
One possible replacement for memset
when you have an array of object types is to use the std::fill
algorithm. It works with iterator ranges and also with pointers into arrays.
memcpy
calls can usually be replaced with calls to std::copy
.
e.g.
std::copy(name, name + strlen(name) + 1, oldname);
// ...
std::fill(name, name + strlen(name), '\0');
memset
and memcpy
are still there and can be used when appropriate, though. It's probably a bigger no-no from many C++ developer's point of view to be using a raw new
and not using a resource managing object. It's much better to use a std::string
or a std::vector<char>
so that memory deallocation is automatic and the code is more exception safe.
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