Consider the two following prototypes:
template<class T>
void whatever1(const T& something);
template<class T>
void whatever2(T const& something);
They are both identical. Yet what if T
is not a usual type, but a pointer type? For instance, let T
be Somewhere*
then whatever1
and whatever2
would have different interpretation:
// nonconst pointer (passed by reference) to const object
void whatever1(const Somewhere*& something);
// const pointer (passed by reference) to nonconst object
void whatever2(Somewhere* const& something);
In this case, I can infer the following properties:
1 whatever1
:
a) can modify something
inside and these changes propagate to the outside;
b) object pointed by something
cannot be modified.
2 whatever2
:
a) cannot modify something
inside so it is safe outside;
b) object pointed by something
can be modified.
Usually const
and &
are used together to avoid copying when passing a parameter and to protect this parameter from modification at the same time. Then in terms of this philosophy only whatever2
fulfills its role. However, if I want the object pointed by something
to be also non-modifiable, then none of two is suitable! Then what would be? Maybe this joke:
template<class T>
void whatever3(const T const& something);
In addition to this confusion some people use whatever1
style, while others use whatever2
one. Which one should be used when creating generic classes and methods as a rule of thumb?
Note that if we start considering Somewhere**
as T
things get even more confusing.
void whatever1(const Somewhere*& something);
is not a correct translation. It would in fact bevoid whatever1(Somewhere* const& something);
, the same aswhatever2
. – ildjarn Apr 9 '12 at 22:06