13

I know this is a very basic, probably even embarrassing, question, but I'm having trouble understanding this. If I std::move from something on the stack to another object, can the other object still be used when the original goes out of scope?

#include <iostream>
#include <string>

int
main(int argc, char* argv[])
{
    std::string outer_scope;

    {
        std::string inner_scope = "candy";
        outer_scope = std::move(inner_scope);
    }

    std::cout << outer_scope << std::endl;

    return 0;
}

Is outer_scope still valid where I'm trying to print it?

firebush
  • 5,180
  • 4
  • 34
  • 45
  • 4
    Yes of course. The whole point of move constructor/assignment is to steal contents from temporaries - it would be pretty useless if the object thus constructed could not be used after the temporary in question dies. – Igor Tandetnik Oct 05 '16 at 18:03
  • If you move something then that means what you moved it to is now in control and the thing that had control no longer does. – NathanOliver Oct 05 '16 at 18:03
  • Of course it is – MikeMB Oct 05 '16 at 18:04
  • @πάνταῥεῖ Huh? The code looks pretty straightforward and non-controversial to me. Which rule, in your opinion, does it run afoul of? – Igor Tandetnik Oct 05 '16 at 18:04
  • @IgorTandetnik Sorry I misinterpreted for the vice versa action. There's a dupe for that one though. – πάντα ῥεῖ Oct 05 '16 at 18:05
  • It's perfectly legal to move a stack object into another object. However, the only thing that has to be guaranteed to work on the hollow husk of the moved object is its destructor, so you will usually want to stop using it once its guts have been transferred somewhere else. – zneak Oct 05 '16 at 18:16
  • @zneak you can do anything that has no preconditions, such as assigning a different value to it. – Caleth Oct 01 '20 at 11:11

1 Answers1

7

Yes it's still valid, the innerscope object loses ownership of the content it previously had, and outerscope becomes the owner. std::move is like a vector swap. If you swap outer and inner, destroying inner won't affect the content now owned by outer.

Jules G.M.
  • 3,624
  • 1
  • 21
  • 35