Search code examples
c++copy-constructorassignment-operator

copy constructors in structs: Do arrays get copied


I have a question about the copy constructor behaviour in C++. I have a struct as follows:

struct Vec4
{
public:
   float elems[4];

};

Now if I do something like:

Vec4 copied = some_func(); // returns a Vec4 object

Will this perform a deep copy of the elms array or would it just copy the pointer address? I am thinking it should be the latter and an explicit copy constructor and assignment operator should be provided but am not sure.

I did a small test and it does what it is supposed to do but I am not sure if that is just an accident!


Solution

  • Yes, elems is a subobject of a Vec4 object, so it gets copied along with the Vec4. There is no pointer to be copied. The array elements are literally embedded inside the Vec4 object.

    I find the terms deep- and shallow-copy a little misleading in C and C++. I think a better way to think about it is that a defaulted copy will not follow any levels of indirection (such as pointers). You can have a really "deep" object (lots of subobjects of subobjects and so on) where no indirection is involved and still the whole thing would be copied, yet we still call this a "shallow copy". If you need to follow any indirection, you need to implement a custom copy constructor that does a "deep copy".