【问题标题】:What does && mean at the end of a function signature (after the closing parenthesis)? [duplicate]函数签名末尾的 && 是什么意思(在右括号之后)? [复制]
【发布时间】:2013-02-25 12:48:04
【问题描述】:

Workarounds for no 'rvalue references to *this' feature 中,我看到以下成员函数(一个转换运算符):

template< class T >
struct A
{
    operator T&&() && // <-- What does the second '&&' mean?
    {
        // ...
    }
};

第二对&amp;&amp; 是什么意思?我不熟悉那种语法。

【问题讨论】:

  • && ref-qualifier:所有声明 T() 都有一个 ref-qualifier:Link

标签: c++


【解决方案1】:

这是一个参考值限定符。这是一个基本示例:

// t.cpp
#include <iostream>

struct test{
  void f() &{ std::cout << "lvalue object\n"; }
  void f() &&{ std::cout << "rvalue object\n"; }
};

int main(){
  test t;
  t.f(); // lvalue
  test().f(); // rvalue
}

输出:

$ clang++ -std=c++0x -stdlib=libc++ -Wall -pedantic t.cpp
$ ./a.out
lvalue object
rvalue object

取自here

【讨论】:

    【解决方案2】:

    表示该函数只能在右值上调用。

    struct X
    {
          //can be invoked on lvalue
          void f() & { std::cout << "f() &" << std::endl; }
    
          //can be invoked on rvalue
          void f() && { std::cout << "f() &&" << std::endl; }
    };
    
    X x;
    
    x.f();  //invokes the first function
            //because x is a named object, hence lvalue
    
    X().f(); //invokes the second function 
             //because X() is an unnamed object, hence rvalue
    

    Live Demo 输出:

    f() &
    f() &&
    

    希望对您有所帮助。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多