gpt4 book ai didi

c++ - 为什么右值在使用后不立即销毁?

转载 作者:太空狗 更新时间:2023-10-29 19:57:40 25 4
gpt4 key购买 nike

我编写了以下程序并期望从 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 中所述

rvalues denote temporary objects which are destroyed at the next semicolon

我做错了什么?

最佳答案

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

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

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

有很好的引用 here这详细解释了右值引用,也许这会澄清一些事情。

关于c++ - 为什么右值在使用后不立即销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31252615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com