警告 C26815
指针处于悬空状态,因为它指向已销毁的临时实例。 (ES.65)
注解
创建的指针或视图是指在语句末尾销毁的未命名临时对象。 指针或视图将会悬空。
此检查可识别 C++ 标准模板库 (STL) 中的视图和所有者。 要教授此检查用户创作的类型,请使用 [[msvc::lifetimebound]]
批注。
[[msvc::lifetimebound]]
支持是 MSVC 17.7 中的新增功能。
代码分析名称:LIFETIME_LOCAL_USE_AFTER_FREE_TEMP
示例
请考虑在 C++23 之前的 C++ 版本中编译的以下代码:
std::optional<std::vector<int>> getTempOptVec();
void loop() {
// Oops, the std::optional value returned by getTempOptVec gets deleted
// because there is no reference to it.
for (auto i : *getTempOptVec()) // warning C26815
{
// do something interesting
}
}
void views()
{
// Oops, the 's' suffix turns the string literal into a temporary std::string.
std::string_view value("This is a std::string"s); // warning C26815
}
struct Y { int& get() [[msvc::lifetimebound]]; };
void f() {
int& r = Y{}.get(); // warning C26815
}
可以通过延长临时对象的生存期来修复这些警告。
std::optional<std::vector<int>> getTempOptVec();
void loop() {
// Fixed by extending the lifetime of the std::optional value by giving it a name.
auto temp = getTempOptVec();
for (auto i : *temp)
{
// do something interesting
}
}
void views()
{
// Fixed by changing to a constant string literal.
std::string_view value("This is a string literal");
}
struct Y { int& get() [[msvc::lifetimebound]]; };
void f() {
Y y{};
int& r = y.get();
}