代码之家  ›  专栏  ›  技术社区  ›  cpp_enthusiast

std::optional operator*()[duplicate]中函数调用后的const&/&/const&&&/&&

  •  0
  • cpp_enthusiast  · 技术社区  · 7 年前

    最近我在通读 API of boost::optional

    T const& operator *() const& ;
    T&       operator *() & ;
    T&&      operator *() && ;
    

    我还编写了自己的程序,将成员函数定义为const&&和&&(注意,我说的不是返回类型,而是分号前面的说明符,它们似乎工作正常。

    我知道声明成员函数const意味着什么,但是有人能解释一下声明它const&意味着什么吗&和&&。

    0 回复  |  直到 11 年前
        1
  •  48
  •   Dan Nissenbaum AndrewMcLagan    8 年前

    const&

    const A a = A();
    *a;
    

    & 意味着这个重载将只用于非常量对象。

    A a;
    *a;
    

    && 意味着,此重载将仅用于rvalue对象。

    *A();
    

    有关C++ 11标准的这个特性的更多信息,您可以阅读此帖子。 What is "rvalue reference for *this"?

        2
  •  41
  •   Alper    11 年前

    它是成员函数REF限定符,它是C++ 11中添加的特性之一。 this 通过指定函数ref限定符,对象参数是左值或右值( some details ).

    & &&

    #include <iostream>
    struct myStruct {
        void func() & { std::cout << "lvalue\n"; }
        void func() &&{ std::cout << "rvalue\n"; }
    };
    
    int main(){
        myStruct s;
        s.func();            // prints "lvalue"
        std::move(s).func(); // prints "rvalue"
        myStruct().func();   // prints "rvalue"
    }