What is the difference between "std::string const &s" and "const std::string &s"?

Thomas Good picture Thomas Good · Mar 10, 2016 · Viewed 16.1k times · Source

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 :)

Answer

manlio picture manlio · Mar 10, 2016

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 the const 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 as static double const x = 3.14;. Basically every const ends up on the right of the thing it constifies, including the const 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).