Avviso C26815
Il puntatore è incerto perché punta a un'istanza temporanea che è stata eliminata. (ES.65)
Osservazioni:
Il puntatore o la vista creata fa riferimento a un oggetto temporaneo senza nome eliminato alla fine dell'istruzione. Il puntatore o la vista si districherà.
Questo controllo riconosce le visualizzazioni e i proprietari della libreria di modelli standard (STL) C++. Per insegnare a questo controllo sui tipi creati dall'utente, usare l'annotazione [[msvc::lifetimebound]]
.
Il [[msvc::lifetimebound]]
supporto è una novità di MSVC 17.7.
Nome dell'analisi del codice: LIFETIME_LOCAL_USE_AFTER_FREE_TEMP
Esempio
Prendere in considerazione il codice seguente compilato in una versione C++ precedente a 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
}
Questi avvisi possono essere corretti estendendo la durata dell'oggetto temporaneo.
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();
}