Search code examples
c++c++11move-semantics

Return moveable member variable from class


class foo{
public:
    bar steal_the_moveable_object();
private:
    bar moveable_object;
};

main(){
    foo f;
    auto moved_object= f.steal_the_moveable_object();
}

How can implement steal_the_movebale_object to move the moveable_object into the moved_object ?


Solution

  • You can simply move the member directly in the return statement :

    class foo
    {
    public:
        bar steal_the_moveable_object()
        {
            return std::move(moveable_object);
        }
    private:
        bar moveable_object;
    };
    

    Beware that this may not be a good idea though. Consider using the following instead so that the member function can only called on an rvalue :

    class foo
    {
    public:
        bar steal_the_moveable_object() && // add '&&' here
        {
            return std::move(moveable_object);
        }
    private:
        bar moveable_object;
    };
    
    int main()
    {
        foo f;
        //auto x = f.steal_the_moveable_object(); // Compiler error
        auto y = std::move(f).steal_the_moveable_object();
    
        return 0;
    }