Clang:使用-Wdangling-gsl和大括号初始化没有警告,这是clang的bug吗?

3
考虑以下代码片段:
#include <string>
#include <string_view>

int main() {
  auto str = std::string{};

  auto sv1 = std::string_view(str + "!"); // <- warning :)
  std::string_view sv2(str + "!");        // <- warning :)
  std::string_view sv3 = str + "!";       // <- warning :)

  auto sv4 = std::string_view{str + "!"}; // <- no warning :(
  std::string_view sv5{str + "!"};        // <- no warning :(
}

使用编译器选项-std=c++17 -Wdangling-gsl编译。在clang 12.0.1和编译器浏览器中测试通过。

预计,在sv1sv2sv3中,str + "!"会触发警告:

Object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]

然而在 sv4sv5 中,使用 {} 的相同表达式却不起作用。
这是使用 {} 的预期行为吗?这是clang的一个bug吗?还是我忽略了什么?
1个回答

3
这是clang诊断程序中的一个错误。你在最后两个案例中使用花括号并不能“修复”悬空指针问题。
通过“确认”,Visual Studio/MSVC中的代码分析工具(静态分析器)会对所有五个svX变量发出以下警告:
warning C26449: gsl::span or std::string_view created from a temporary will be invalid when the temporary is invalidated (gsl.view).
warning C26815: The pointer is dangling because it points at a temporary instance which was destroyed.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接