This is exactly as you said.
When you pass an object by value, its copy constructor is called to create a new instance of such an object, which will be used inside the function. Changes made to this new facility will not be reflected in the original 1 .
As with structures, the default copy constructor simply executes a shallow copy of the original object, that is, its fields are copied to a new instance 2 ; in many cases this is undesirable (for example, if the object wraps a pointer / other resource), therefore there are classes that override the copy constructor or completely disable it. The objects of these last classes can only be passed in by pointer or by reference.
Passing objects by value can be expensive if they are larger than a pointer (in size) or even if their copy constructor is not "cheap." Compared to pointers, on the other hand, throughput provides the usual advantages of not having to point to a pointer, letting the caller do whatever they want with the object, etc.
Note that passing an object by value kills polymorphism. This is because the function that receives the object by value receives a statically typed object with the exact size and type, so any attempt to pass an object of a derived class will split the objects (the copy constructor for the base class is called, which by default simply copies the fields available in the base class).
This is why the often preferred method for passing objects is through a const reference. This has several advantages:
- no copies; the object that the called person will see will be exactly the one indicated at the time of the call;
- No changes to the original object can be made, thanks to the
const qualifier; - if the called call needs to change a copy of the object, it can still create a copy from the link;
- lack of fuzzy pointer syntax;
- polymorphism persists, since behind the scenes we actually transmit the pointer;
- There is little doubt that the object belongs to: the general rule about links is that they belong to the caller.
As for the "raw fields" of the object; Naturally, if the source object and the copy continue to share the pointer / descriptor on the same resource, some changes may affect others.
Primitive types (and POD in general) are copied bitwise, and the copy constructor is called for non-POD types.
Matteo italia
source share