gpt4 book ai didi

c++ - 为左值 move 语义

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:42 25 4
gpt4 key购买 nike

我做了简单的测试来更好地理解 move 语义。输出结果出乎我的意料。下面是我的测试函数:

template<class T>
void test(T&& v)
{
v++;
}

void main()
{
int v = 1;
test(std::move(v));
std::cout << "Output:" << v << std::endl;
}

我的期望是:输出:1但真正的结果是:输出:2

我的想法如下 - 我使用 std::move(v),结果我转换为“右值”并且测试函数将使用时间变量。因此结果应该是输出:1。我的结论有什么问题?

最佳答案

std::move 从不构造临时对象。它是到右值引用的转换。

这个引用绑定(bind)到 main::v,然后 test::v 参数用它初始化,因此也绑定(bind)到 main::v

如果你想创建一个临时的,使用强制转换:

test(int{v});

关于c++ - 为左值 move 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44307776/

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