What is the difference between “std::string const &s” and “const std::string &s”?
我一直在寻找有关如何做某事的示例,并看到了这两种变体:
1 2 | std::string const &s; const std::string &s; |
在不同的片段中。
谢谢你的回答:)
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.
(有关更多详细信息,请参见" X const&x"和" X const * p"是什么意思)。
如果决定使用const on-the-right样式,请确保不要将
上面的声明意味着:"
这是多余的,因为引用始终为
从技术上讲,它是相同的,没有任何区别。但是,在某些调试器(肯定是lldb)中,即使您编写为
正如Barry在回答中所指出的那样,旧的C语法(以及该语法的C ++扩展名)不像数学中那样支持文本替换的概念性视图。
因此,直接使用C语法通常是写
几个月前,我开始编写
1 2 | template< class Some_type > using Ptr_ = Some_type*; |
因此,而不是从右到左读取
1 | char const* const p = something; |
我可以写普通的阅读方向
1 | const Ptr_<const char> p = something; |
它有点冗长,但是我现在有了一些使用它的经验,认为这是值得的(我不确定那是实验)。
主要缺点是,尽管此表示法支持(功能模板)函数参数的类型推导,就像直接使用C语法一样,但它不支持
对于我当前的类型生成器,例如
如前所述,它们是同一类型。喜欢右侧
1 2 3 4 | template <class T> void foo(const T& arg); int* p; foo(p); |
1 | template <class T> void foo(T const& arg); |
然后,简单的文本替换将产生正确的类型:
只是为了证明其他人的断言(我了解rtti不会在
这个测试程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <string> #include <iostream> using std::string; using std::cout; using std::cin; using std::endl; int main() { std::string t ="BLABLA" ; std::string t1 ="BLABLA" ; std::string const &s = t; const std::string &d = t1; if (typeid(d) == typeid(s)) cout <<"d and s are the same type according to the rtti" << endl; else cout <<"d and s are the NOT the same type according to the rtti" << endl; // here the raw output is exactly the same for both cout << typeid(d).raw_name() << endl << typeid(s).raw_name() << endl; cin >> t; return 0; } |
对于gcc(4.9.2),两者都具有正确的修改。msdn(vs2010)对于两者均返回"相同类型"。
我将此"答案"作为贡献而不是"答案"。
编辑:阅读Scott-Meyers的" Effective Modern C ++"中的第4项,分享了有关我编写的示例的一些非常有趣的隐藏信息。
简而言之,由于我们通过值传递变量名,因此typeid不会产生可靠的结果。
当我们通过值传递变量的方法时,推导的类型将失去其常量性,易变性和参考性(因为对上帝的爱将被缩短为cvr)。这就是为什么上面的示例无法证明两种类型之间是否存在差异的原因。
同一项目指出,Boost项目托管一个名为TypeIndex的库,该库保留了cvr属性。