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
firebush
6,1346 gold badges43 silver badges62 bronze badges
-
4Yes 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– Igor Tandetnik2016年10月05日 18:03:25 +00:00Commented 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.NathanOliver– NathanOliver2016年10月05日 18:03:56 +00:00Commented Oct 5, 2016 at 18:03
-
Of course it isMikeMB– MikeMB2016年10月05日 18:04:19 +00:00Commented 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?Igor Tandetnik– Igor Tandetnik2016年10月05日 18:04:30 +00:00Commented Oct 5, 2016 at 18:04
-
@IgorTandetnik Sorry I misinterpreted for the vice versa action. There's a dupe for that one though.πάντα ῥεῖ– πάντα ῥεῖ2016年10月05日 18:05:21 +00:00Commented Oct 5, 2016 at 18:05
1 Answer 1
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
Jules Gagnon-Marchand
3,8011 gold badge24 silver badges35 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-cpp