Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 526
Humam Helfawi Avatar asked Jan 03 '17 20:01

Humam Helfawi


1 Answers

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 method can only called on R-Values :

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;
}
like image 189
François Andrieux Avatar answered Sep 24 '22 03:09

François Andrieux