gpt4 book ai didi

c++ - &&、基于范围的循环和临时变量如何协同工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:14:44 27 4
gpt4 key购买 nike

我看到下面的代码here .描述说:

We can also capture as a forwarding reference using auto&&. That is, auto&& will resolve to auto& for lvalue references, and auto&& for rvalud references. Here is an example of capturing the output from a range-based for loop over a temporary map.

如果引用的值是左值(因此在这种情况下没有衰减),我确实理解 auto&&auto& 的衰减。我苦苦挣扎的是了解临时 map 、基于范围的 for 循环和移动的值如何协同工作。您是否愿意解释一下这些东西如何相互配合以及为什么可以从正在迭代的临时文件中移出。

#include <iostream>
#include <map>

std::map<std::string, int> get_map()
{
return {
{ "hello", 1 },
{ "world", 2 },
{ "it's", 3 },
{ "me", 4 },
};
}

int main() {
for (auto&& [ k, v ] : get_map())
std::cout << "k=" << k << " v=" << v << '\n';
}

最佳答案

本例中auto&&有两种不同的用法,一种可见,一种隐藏。为了尽可能冗长,您的循环扩展为:

{
auto&& __range = get_map(); // the temporary get_map() is bound to a reference, which
// extends its lifetime to the lifetime of the reference
// decltype(__range) is std::map<std::string, int>&&

auto __begin = __range.begin();
auto __end = __range.end(); // potential different type from __begin since C++17
for (; __begin != __end; ++__begin) {
auto&& __elem = *__begin; // this is your structured binding declaration
// *__begin is an lvalue, so decltype(__elem) is
// std::pair<std::string const, int> const&


// the actual destructuring here
std::string const& k = std::get<0>(__elem);
int const& v = std::get<1>(__elem);

// now your body
std::cout << "k=" << k << " v=" << v << '\n';
}
}

因此:

why it's ok to move from a temporary that is being iterated.

这段代码中没有任何地方发生移动。 map 是在 __range 中构建的,这就是您要迭代的内容。它超出了最后一个括号的范围。


请注意:

I do understand the decaying of auto&& to auto& if the value referred to is an lvalue

不太正确。首先,它不被称为“衰减”——衰减是当你将一个数组传递给一个函数时发生的事情——它衰减成一个指针。此外,auto&& 不会折叠成 auto&。只是,如果初始化器是左值,auto&&auto& 的行为方式相同。如果初始化器是一个右值,auto&& 工作(并产生一个右值引用)而 auto& 编译失败。

关于c++ - &&、基于范围的循环和临时变量如何协同工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45576754/

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