函数后面的 const &、const &&、&、&& ?

nm1*_*m17 5 c++ class

我目前正在查看一些内部基础设施代码,我看到了一些这样定义的函数:

// func_name is a class member function

some_return_type func_name() & {
  // definition
}

some_return_type func_name() && {
  // definition
}

some_return_type func_name() const& {
  // definition
}

some_return_type func_name() const&& {
  // definition
}
Run Code Online (Sandbox Code Playgroud)

我知道const在类成员函数名称之后意味着它不会修改类中定义的不可变成员变量。但这里的&&&const &const &&变体是什么意思呢?

Ded*_*tor 9

使用self作为调用方法的对象:

  1. self必须匹配Type&

    some_return_type func_name() &;
    
    Run Code Online (Sandbox Code Playgroud)
  2. self必须匹配Type&&(并且也将匹配Type const&&Type const&):

    some_return_type func_name() &&;
    
    Run Code Online (Sandbox Code Playgroud)
  3. self必须匹配Type const&&(并且也将匹配Type const&):

    some_return_type func_name() const&&;
    
    Run Code Online (Sandbox Code Playgroud)
  4. self必须匹配Type const&

    some_return_type func_name() const&;
    
    Run Code Online (Sandbox Code Playgroud)

self正如您所看到的,如果 C++ 从一开始就有引用,并选择-references 而不是this-pointers,那么理解会更容易。

Cppreference.com 上的 ref-qualified member-functions