gpt4 book ai didi

c++ - 为什么 Clang 的 -Wrange-loop-analysis 在带有 std::string_view 变量的 for 循环中发出警告? std::string_view 不是引用吗?

转载 作者:行者123 更新时间:2023-12-01 23:01:49 33 4
gpt4 key购买 nike

我有这个循环:

for (const std::string_view resource : resources) { ... }

由此资源被定义为

inline const std::string_view resources[] = { ... } 

但是我得到这个错误:

error: loop variable 'resource' of type 'const std::string_view' (aka 'const basic_string_view<char>') creates a copy from type 'const std::string_view' [-Werror,-Wrange-loop-analysis]

这是为什么。我以为std::string_view只是对实际数据的引用。但在这里它被复制了?

最佳答案

Why is that.

你制作了一个拷贝,因为循环变量不是引用(并且与元素具有相同的类型)。

I thought std::string_view was just a reference to the actual data.

这就是它在概念上的含义。更具体地说,它是一个包含指向数据的指针和大小(或者指向末尾的指针;这无关紧要)的类。您复制了这个概念性的“引用”,即那个类实例。


请注意,-Wrange-loop-analysis 默认情况下未启用,-Wall-Wextra 均未启用(至少在 Clang 中9).这种“警告”通常并不一定意味着程序有任何问题。它们可能是信息性提示,也可能具有很高的误报率。

自版本 10 以来,Clang 不再为给定示例生成警告。发行说明是这样说的:

-Wrange-loop-analysis got several improvements. ... It no longer warns when an object of a small, trivially copyable type is copied.

因此,我建议的解决方案是升级您的编译器和/或不要显式启用 -Wrange-loop-analysis

关于c++ - 为什么 Clang 的 -Wrange-loop-analysis 在带有 std::string_view 变量的 for 循环中发出警告? std::string_view 不是引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71665376/

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