我编写了以下程序,并期望从 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;
}
但事实并非如此。改为产生以下输出:
foo()
before ending the program
~A()
DEMO
正如 answer 中所说
我做错了什么?
最佳答案
std::move
不会将 a
变成临时值。相反,它创建了对 a
的右值引用,该引用在函数 foo
中使用。在这种情况下 std::move
没有为您做任何事情。std::move
的要点是您可以指示应该使用 move 构造函数而不是复制构造函数,或者被调用的函数可以自由地以破坏性的方式修改对象。它不会自动导致您的对象被破坏。
所以 std::move
在这里所做的是,如果它愿意,函数 foo
可以以破坏性的方式修改 a
(因为它接受一个右值引用作为它的参数)。但是 a
仍然是一个左值。只有引用是右值。
有一个很好的引用 here 详细解释了右值引用,也许这会澄清一些事情。
关于c++ - 为什么右值在使用后不会立即销毁?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31252615/