I have a pointer to raw data using const u_char*, and a generic class like this
class Rectangle
{
u_int8_t length;
u_int8_t height;
...
}
Assuming the raw data is a binary “stream” of bytes, what is the best way to get the raw data into the fields of the class.
-memcpy ?
-cast ?
i could do this :
Rectangle *rect = (Rectangle*)rawdata;
but i know that is a “old style” cast.
What is the proper way ?
The easiest and most reliable method is to simply use a convert constructor:
This should be your go-to method until for whatever reason this is impossible.
Barring this, the next best thing to do is simply do a memberwise initialization:
If it becomes impossible to do the above, and iff the object in question is what the Standard refers to as an “aggregate” (basically a POD), you can use an initializer like this:
When doing this, you must bear in mind that the members will be initialized in the order in which they are declared in the class. If you change the order of declaration, you will break every initialization like the above. This is very brittle. For this reason, I limit my use of a construct like this to cases where the class in question is highly localized (like a helper class in a single translation unit), and I document the need to keep the order of declaration intact.
EDIT PER COMMENTS:
In the instance you are trying to copy strings in to your class, or pointers to any sort of data, you will need to do a deep copy:
Note the clumsiness and how brittle the above code is. There are plenty of things that could go wrong here. Not the least of which are forgetting to
deletestr_whenGizmois destroyed, the ugliness and seeming lack of necessity fornewing acharstring in the first place, one-past-the-end errors … the list goes on. For these reasons, it’s best to avoid using raw pointers at all and using either smart pointers (ieunique_ptr,shared_ptr, etc) or collection classes. In this case, I’d use astd::string, which can be thought of as a collection class:Feel free to convert this for use with a
u_char*, and to add robustness by means of verifying the source pointer is valid.