Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement method with ref qualifier

Tags:

c++

c++11

I have trouble to implement following code

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();
}

The problem is that I can't call getVector inside getVectorAndMore because this is not rvalue. To make the code compile, I had to cast this to rvalue.

Is any good way to implement such code?


with return getVector();

error message is

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.

Coliru

like image 743
Bryan Chen Avatar asked May 06 '14 08:05

Bryan Chen


1 Answers

return getVector(); // not compile

This is equivalent to this:

return this->getVector(); // not compile

which wouldn't compile, because this is an lvalue, not an rvalue and getVector() can be invoked only on rvalue, hence the error.

Note that this is always an lvalue — even inside rvalue-ref member function!


return std::move(*this).getVector();

That is the correct way to invoke getVector().

like image 55
Nawaz Avatar answered Sep 20 '22 21:09

Nawaz