函数声明符的右值、左值引用以及const引用

来源:互联网 发布:sql dump transaction 编辑:程序博客网 时间:2024/05/17 03:52

  有这么一段代码:

 

#include <iostream>void func(){ return;}int main(){auto& lref = func;auto const& clref = func;auto && rref = func;auto const&& crref = func;getchar();return 0;}</span>


  通过 VS 的 Tooltip,可以看到

  lref : void(&)();

  clref : void(&)();

  rref : void(&)();

  crref : void(&&)()。

  那么问题就来了:

  1.为什么第三个是一个左值引用?

  2.const哪去了?


  首先,auto的推导规则和模板推导原则一致。看过C++ Primer中后面的章节对于std::move的讲解后,可以知道T&&,如果给它传一个左值进去T就会是类型的引用,经过折叠(T& &&)就会成为T&。

  那么func是左值还是右值呢?

  “C++11标准,5 Expressions,§6

  rvalue references to functions are treated as lvalues whether named or not. ” 

  左值。


  那么第二个问题就来了:为什么第四个就是右值?


  "Universal references can only occur in the form “T&&”!  Even the simple addition of a const qualifier is 

enough to disable the interpretation of “&&” as a universal reference"


  http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers

  所以嘛...


  至于失踪的const嘛...

  C++11标准,8.3.5 Functions,§6
"The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored. [ Note: a function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types. — end note ]"


  感谢木头云大牛的指导以及MoGu大牛的问题。



0 0
原创粉丝点击