考虑以下片段:
#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 和主干中测试。
正如预期的那样,在 sv1
、sv2
和 sv3
中,str + "!"
触发警告:
Object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]
但是在 sv4
和 sv5
中,相同的表达式,但使用 {}
,却不是。
这是使用 {}
的预期行为吗?这是 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/