“ std :: string const& s”和“ std :: string const& s”之间有什么区别?和“ const std :: string& s”?
我一直在寻找有关如何做某事的示例,并看到了这两种变体:
I was looking for examples on how to do something and saw this two variants:
std::string const &s;
const std::string &s;
不同的摘要。
thx for您的答案:)
thx for your answer :)
std :: string const&
是等同于 const std :: string&
。
const std :: string& ;
是Stroustrup的 C ++编程语言中采用的样式,并且可能是传统样式。
const std::string &
is the style adopted in Stroustrup's The C++ Programming Language and probably is "the traditional style".
std :: string const& 可能比替代方法更一致:
std::string const &
can be more consistent than the alternative:
the const-on-the-right样式始终将
const
置于其所表示的内容的右侧,而另一种样式有时会将const
在左侧,有时在右侧。
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.
使用const-on-the-right样式,可以用const定义const局部变量。在右边: int const a = 42;
。同样,将const静态变量定义为 static double const x = 3.14;
。基本上,每个 const
都位于它所构成的事物的右侧,包括 const
必须位于正确:具有const成员函数。
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.
(请参见 X const& x和 X const * p是什么意思?)。
如果您决定使用const-on-the-right样式,请确保不要误输入 std :: string const& s
作为荒谬的 std :: string& const s
:
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
:
以上声明的意思是: s
是 const
引用 std :: string
。
这是多余的,因为引用始终为 const
(您永远都不能重置引用以使其引用其他对象)。
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).