我正在寻找有关如何做某事的示例,并看到了这两种变体:
std::string const &s;
const std::string &s;
在不同的片段中。
谢谢你的回答:)
最佳答案
std::string const &
等价于 const std::string &
。
const std::string &
是Stroustrup的The C++ Programming Language采用的风格,大概是“传统风格”。
std::string 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.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.
(参见 What do “X const& x” and “X const* p” mean? 了解更多详情)。
如果您决定使用 const-on-the-right 样式,请确保不要将 std::string const &s
错误输入为无意义的 std::string &常量 s
:
上述声明的意思是:“s
是 const
对 std::string
的引用”。
这是多余的,因为引用总是 const
(您永远不能重置引用以使其引用不同的对象)。
关于c++ - "std::string const &s"和 "const std::string &s"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35913098/