Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::move on a stack object

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?

like image 734
firebush Avatar asked Oct 05 '16 18:10

firebush


1 Answers

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.

like image 122
Jules G.M. Avatar answered Sep 18 '22 09:09

Jules G.M.