为什么右值在使用后不会立即销毁?

use*_*882 3 c++ move-semantics

我编写了以下程序,并期望从中获得的右值std::move()在函数调用中使用后会立即被销毁:

struct A
{
    A(){ }
    A(const A&){ std::cout << "A&" << std::endl; }
    ~A(){ std::cout << "~A()" << std::endl; }
    A operator=(const A&){ std::cout << "operator=" << std::endl; return A();}
};

void foo(const A&&){ std::cout << "foo()" << std::endl; }

int main(){
    const A& a = A();
    foo(std::move(a)); //after evaluation the full-expression 
                       //rvalue should have been destroyed
    std::cout << "before ending the program" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但事实并非如此。改为产生以下输出:

foo()
before ending the program
~A()
Run Code Online (Sandbox Code Playgroud)

演示

正如答案中所说

右值表示在下一个分号处销毁的临时对象

我做错了什么?

rlb*_*ond 6

std::move不会a变成临时值。相反,它创建了一个对 的右值引用a,在函数中使用foo。在这种情况下std::move是不为你做任何事情。

重点std::move是您可以指示应该使用移动构造函数而不是复制构造函数,或者被调用的函数可以自由地以破坏性的方式修改对象。它不会自动导致您的对象被破坏。

所以std::move这里的作用是,如果它想要,函数foo可以a以破坏性的方式修改(因为它需要一个右值引用作为它的参数)。但a仍然是一个左值。只有引用是右值。

有一个很好的参考这里是详细解释了右值引用,也许这将清除一些东西。