std ::在堆栈对象上移动

fir*_*ush 7 c++ move-semantics c++11

我知道这是一个非常基本的,甚至可能是令人尴尬的问题,但我无法理解这一点.如果我std ::从堆栈上的东西移动到另一个对象,当原始文件超出范围时,是否还可以使用另一个对象?

#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;
}
Run Code Online (Sandbox Code Playgroud)

在我尝试打印时,outer_scope仍然有效吗?

Jul*_*.M. 6

是的,它仍然有效,内部作用域对象失去了它以前拥有的内容的所有权,外部作用域成为所有者。std::move 就像一个向量交换。如果交换外部和内部,销毁内部不会影响现在由外部拥有的内容。