Edit

Share via


Warning C26815

The pointer is dangling because it points at a temporary instance that was destroyed. (ES.65)

Remarks

The created pointer or view refers to an unnamed temporary object that is destroyed at the end of the statement. The pointer or view will dangle.

This check recognizes views and owners from the C++ Standard Template Library (STL). To teach this check about user-authored types, use the [[msvc::lifetimebound]] annotation. The [[msvc::lifetimebound]] support is new in MSVC 17.7.

Code analysis name: LIFETIME_LOCAL_USE_AFTER_FREE_TEMP

Example

Consider the following code compiled in a C++ version before C++23:

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
}

These warnings can be fixed by extending the lifetime of the temporary object.

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();
}

See also

C26816
ES.65: Don't dereference an invalid pointer