Parameters can be taken in many different ways:
void foo(T obj);
void foo(const T obj);
void foo(T& obj);
void foo(const T& obj);
void foo(T&& obj);
void foo(const T&& obj);
I didn't include taking a parameter via a pointer because a pointer could already be the type T
.
The first two ways are taking the object by value which will cause the object to get copied (if not optimized by a smart compiler).
The other ways take the object by reference (the first two by a l-value reference and the last two as a r-value reference) which should omit making any copies. The const
qualified versions promise not to modify the referenced object.
If I want my function to be able to take as parameters all kinds of values (variables, temporaries returned from functions, literals etc.) what should be its prototype for a not-object-modifying version (const
) and a potentially-object-modifying version (not const
) version, if I want it to be the most efficent (avoid invoking copy constructors, move constructors, assignment operators, creating temporaries etc.)?
I'm not sure which type of references should I use. If this is a subjective question I am looking for pros and cons of each approach.