使用ref限定符实现方法

Bry*_*hen 13 c++ c++11

我无法实现以下代码

template <class T>
struct Foo
{
    std::vector<T> vec;

    std::vector<T> getVector() && {
        // fill vector if empty
        // and some other work
        return std::move(vec);
    }

    std::vector<T> getVectorAndMore() &&
    {
        // do some more work
        //return getVector(); // not compile
        return std::move(*this).getVector(); // seems wrong to me
    }
};

int main()
{
    Foo<int> foo;

    auto vec = std::move(foo).getVectorAndMore();
}
Run Code Online (Sandbox Code Playgroud)

问题是我不能getVector在里面打电话,getVectorAndMore因为this它不是右值.为了使代码编译,我不得不转换this为rvalue.

有没有什么好方法可以实现这样的代码?


return getVector();

错误信息是

main.cpp:17:16: error: cannot initialize object parameter of type 'Foo<int>' with an expression of type 'Foo<int>'
        return getVector(); // not compile
               ^~~~~~~~~
main.cpp:26:31: note: in instantiation of member function 'Foo<int>::getVectorAndMore' requested here
    auto vec = std::move(foo).getVectorAndMore();
                              ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

Coliru

Naw*_*waz 13

return getVector(); // not compile
Run Code Online (Sandbox Code Playgroud)

这相当于:

return this->getVector(); // not compile
Run Code Online (Sandbox Code Playgroud)

哪个不会编译,因为它this是一个左值,而不是一个右值,getVector()只能在右值上调用,因此是错误.

注意,this总是一个左值 - 甚至在rvalue-ref成员函数内!


return std::move(*this).getVector();
Run Code Online (Sandbox Code Playgroud)

这是正确的调用方式getVector().