15

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?

asked Oct 5, 2016 at 18:01
7
  • 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. Commented Oct 5, 2016 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. Commented Oct 5, 2016 at 18:03
  • Of course it is Commented Oct 5, 2016 at 18:04
  • @πάνταῥεῖ Huh? The code looks pretty straightforward and non-controversial to me. Which rule, in your opinion, does it run afoul of? Commented Oct 5, 2016 at 18:04
  • @IgorTandetnik Sorry I misinterpreted for the vice versa action. There's a dupe for that one though. Commented Oct 5, 2016 at 18:05

1 Answer 1

9

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.

answered Oct 5, 2016 at 18:07
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.