struct Something
{
int a;
int b;
Something(char* buffer)
{
memcpy(this, buffer, sizeof(Something));
};
};
Is this legal? safe? to me it looks fine but I'm not sure if the C++ standard prohibits it somehow.
struct Something
{
int a;
int b;
Something(char* buffer)
{
memcpy(this, buffer, sizeof(Something));
};
};
Is this legal? safe? to me it looks fine but I'm not sure if the C++ standard prohibits it somehow.
... from the fact that it's no longer a POD type after I added the constructor.
That's no fact (merely fake news ;-) ). Adding a constructor doesn't change a struct
s POD type status.
You can also easily check this with a static_assert
:
static_assert( "Something must be a POD type!",std::is_pod(Something)::value);
Is this legal?
I'm not so sure. Depends on the context. In your's it would work and compile without errors or warnings like intended
safe?
Certainly not.
It calls undefined behavior in various ways.
this
may consist of more than just the data members. There maybe things like a vtable held.You should note, that any kind of reinterpret_cast
(i.e. c-style cast) is giving you undefined behavior to some degree.
You need 100% to know what you're doing, and I recommend to check the emitted assembly output and memory layout every time when you use such constructs.
It is guaranteed to be successfully compiled without error messages. So by definition, it is 100% legal.
In this particular case, it would work as intended. But, if a structure uses virtual functions, it would store vptr, and this thing would not work. You may, for instance, later add a virtual function, and the constructor will stop working. So no, it is not safe.