6
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 ?

Humam Helfawi
  • 17,706
  • 12
  • 64
  • 134

1 Answers1

6

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;
}
François Andrieux
  • 24,129
  • 6
  • 46
  • 72
  • Thanks. In the second option, won't I lose the f object? in real code, foo contains another member varaibles not just the bar one – Humam Helfawi Jan 03 '17 at 20:49
  • @HumamHelfawi: No, `std::move` is only a type-cast in the end. If you're not creating another `foo` object with the moved-from `f`, you're okay. – AndyG Jan 03 '17 at 20:52
  • 1
    `std::move(f)` is a cast to `foo&&`. It does not *actually* invalidate the object. So you could still get the other members but the resulting code would (or should) indeed raise the eyebrows of any future reader. Perhaps you can encapsulate the operation of moving several members in a new method. [std::move is a misnomer](http://stackoverflow.com/questions/21358432/why-is-stdmove-named-stdmove) – François Andrieux Jan 03 '17 at 20:54
  • 1
    To add to my previous comment : `std::move(f);` doesn't do anything to f directly. For example, consider the following function call `sink(std::move(f));`. `f` is still valid at the start of the `sink` function. `std::move` has not made is unusable, it's whatever `sink` decides to do with `f` that may invalidates `f`. – François Andrieux Jan 03 '17 at 21:06
  • huh? && after the function name isn't valid C++. Do you mean add && after the return type, i.e. bar&& steal_the_moveable_object() ??? – Prof Nov 29 '18 at 01:19
  • 1
    @Prof It very well is valid C++ since C++11. See *ref qualifier* [here](https://en.cppreference.com/w/cpp/language/member_functions). The use of a ref qualifier is the entire point of the second part of the answer. It makes the function only callable on a rvalue. – François Andrieux Nov 29 '18 at 12:10