gpt4 book ai didi

c++ - 你能从 c++2a 中的函数返回基于范围的 View 吗?

转载 作者:太空狗 更新时间:2023-10-29 20:07:59 25 4
gpt4 key购买 nike

现在我找不到任何支持 "one ranges proposal" 的编译器所以这更像是一个学术问题。我很好奇以下是否会像我预期的那样工作

#include <iostream>
#include <vector>
#include <ranges>

auto Foo (){
std::vector<int> a = {1,2,3,4,5};
return std::move(a) | std::reverse;
}


int main(){
for(auto a : Foo()){
std::cout << a << std::endl;
}
}

预期输出为

5
4
3
2
1

问题与范围适配器的所有权语义有关。我说我想移动 a 然后用 view 包裹它。预计会发生什么?

  1. 不编译。
  2. 编译但可能因内存损坏而崩溃
  3. 按预期工作

最佳答案

Can you return range based views from functions in c++2a?

你可以。

但是将 View 返回到局部变量或临时变量将毫无用处,因为通过 View 访问被销毁对象的行为是未定义的。与返回迭代器、指针或引用相同。

I say I want to move a and then wrap it with a view. What is expected to happen?

至少按照 ranges-v3 的做法,它静态断言操作数是左值,这导致编译失败。

关于c++ - 你能从 c++2a 中的函数返回基于范围的 View 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689696/

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