c++ - clang 中的 Clang : no warning with -Wdangling-gsl and curly braces initialization, 错误?

标签 c++ compiler-warnings clang++ uniform-initialization

考虑以下片段:

#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 中的错误吗?我只是错过了什么吗?

最佳答案

这是 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.

关于c++ - clang 中的 Clang : no warning with -Wdangling-gsl and curly braces initialization, 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68654097/

相关文章:

C++实现AVL树

c++ - 模板化函数作为参数

c - CodeBlocks 中的奇怪警告 - C

ubuntu - 命名空间 'make_unique' 中没有名为 'std' 的成员

c++ - LLVM:如何交叉编译 C++ 程序

c++ - 在 GDI 资源不足时以编程方式捕获 Windows 关闭事件

c++ - 段错误(核心已转储)C++ 面向对象编程

c++ - 确定比较中文字的有效类型

c# - 不同的 DLL,但在控制台应用程序和网站中应该相同

c++ - 使用-static的 undefined reference ?