C++ Value versus Reference Semantics
- Value semantic
- Value (or
copy
) semantics mean assignment copies the value, not just the pointer. - Reference semantic
- With reference semantics, the assignment is a pointer-copy (i.e., a reference).
Pros of reference semantics: flexibility and dynamic binding (you get dynamic binding in C++ only when you pass by pointer or pass by reference, not when you pass by value).
Pros of value semantics: speed. “Speed” seems like an odd benefit for a feature that requires an object (vs. a pointer) to be copied, but the fact of the matter is that one usually accesses an object more than one copies the object, so the cost of the occasional copies is (usually) more than offset by the benefit of having an actual object rather than a pointer to an object.
There are three cases when you have an actual object as opposed to a pointer to an object: local objects, global/static
objects, and fully contained member objects in a class. The most important of these is the last (composition).