c++ - "std::string const &s"和 "const std::string &s"有什么区别?

标签 c++ c++11 reference constants notation

我正在寻找有关如何做某事的示例,并看到了这两种变体:

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 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.

(参见 What do “X const& x” and “X const* p” mean? 了解更多详情)。

如果您决定使用 const-on-the-right 样式,请确保不要将 std::string const &s 错误输入为无意义的 std::string &常量 s:

上述声明的意思是:“sconststd::string 的引用”。 这是多余的,因为引用总是 const (您永远不能重置引用以使其引用不同的对象)。

关于c++ - "std::string const &s"和 "const std::string &s"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35913098/

相关文章:

C++:方法中的字符串成员别名

rust - 为什么不能在同一结构中存储值和对该值的引用?

c++ - "What happened to my SFINAE"还原 : conditional template class members?

c++ - vector 中的不可复制元素

c++ - 将结构与 std140 对齐,CPU 端

c++ - C++ 和 Qt 中的声音捕获

c++ - 分配另一个 std::vector 的 std::vector 地址

c# - 无法在 C# 中使用我的类库

c++ - 从 bin 文件中读取十六进制数作为每个字符的 2 位数字-c++

c++ - 处理父类对象列表时调用子类的方法