I was looking for examples on how to do something and saw this two variants:
std::string const &s;
const std::string &s;
in different snippets.
thx for your answer :)
std::string const &
is equivalent to const std::string &
.
const std::string &
is the style adopted in Stroustrup's The C++ Programming Language and probably is "the traditional style".
std::string const &
can be more consistent than the alternative:
the const-on-the-right style always puts the
const
on the right of what it constifies, whereas the other style sometimes puts theconst
on the left and sometimes on the right.With the const-on-the-right style, a local variable that is const is defined with the const on the right:
int const a = 42;
. Similarly a static variable that is const is defined asstatic double const x = 3.14;
. Basically everyconst
ends up on the right of the thing it constifies, including theconst
that is required to be on the right: with a const member function.
(see What do “X const& x” and “X const* p” mean? for further details).
If you decide to use const-on-the-right style, make sure to don't mis-type std::string const &s
as the nonsensical std::string & const s
:
The above declaration means: "s
is a const
reference to a std::string
".
It's redundant since references are always const
(you can never reset a reference to make it refer to a different object).