Search code examples
c++memcpymemmove

Using memmove to initialize entire object in constructor in C++


Is it safe to use memmove/memcpy to initialize an object with constructor parameters?
No-one seems to use this method but it works fine when I tried it.
Does parameters being passed in a stack cause problems?

Say I have a class foo as follows,

class foo
{
  int x,y;
  float z;
  foo();
  foo(int,int,float); 
};

Can I initialize the variables using memmove as follows?

foo::foo(int x,int y,float z)
{
  memmove(this,&x, sizeof(foo));
}

Solution

  • This is undefined behavior.

    The shown code does not attempt to initialize class variables. It attempts to memmove() onto the class pointer, and assumes that the size of the class is 2*sizeof(int)+sizeof(float). The C++ standard does not guarantee that.

    Furthermore, the shown code also assumes the layout of the parameters that are passed to the constructor will be the same layout as the layout of the members of this POD. That, again, is not specified by the C++ standard.

    It is safe to use memmove to initialize individual class members. For example, the following is safe:

    foo::foo(int x_,int y_,float z_)
    {
       memmove(&x, &x_, sizeof(x));
       memmove(&y, &y_, sizeof(y));
       memmove(&z, &z_, sizeof(z));
    }
    

    Of course, this does nothing useful, but this would be safe.