共用方式為


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

另請參閱

C26816
ES.65:不要取值不正確指標