gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:43:06 29 4
gpt4 key购买 nike

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

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com