Humam Helfawi
Humam Helfawi

Reputation: 20264

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 ?

Upvotes: 8

Views: 1383

Answers (1)

François Andrieux
François Andrieux

Reputation: 29023

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

Upvotes: 8

Related Questions