ポインターは、スタックに割り当てられたメモリを指します (ES.65)
解説
ポインターは、スタックに割り当てられている変数を指しています。 変数がスコープ外になるとクリーンアップされ、ポインターが無効になります。
このチェックでは、C++ 標準テンプレート ライブラリ (STL) のビューと所有者が認識されます。 ユーザーが作成した型に関するこのチェックを教えるには、 [[msvc::lifetimebound]]
注釈を使用します。
[[msvc::lifetimebound]]
サポートは、MSVC 17.7 の新機能です。
コード分析名: LIFETIME_LOCAL_USE_AFTER_FREE_STACK
例
// In this example, std::string is being used internally because the implementer felt it was easier to
// perform the non-trivial initialization of the value but the function returns a C-style string.
const char *danglingRawPtrFromLocal() {
std::string s;
// interesting string initialization here
return s.c_str(); // Oops, The pointer points to memory that will be cleaned up upon return. Warning C26816.
}
struct Y { int& get() [[msvc::lifetimebound]]; };
int& f() {
Y y;
return y.get(); // Warning C26826
}
修正するには、使用される値が長く存続できるようにします。 この例では、std::string を返すことで警告に対処します。 また、データをヒープにコピーするか、関数パラメーター リストに "out" 変数を追加することで対処することもできます。
std::string danglingRawPtrFromLocal() {
std::string s;
// interesting string initialization here
return s;
}
struct Y { int& get() [[msvc::lifetimebound]]; };
int f() {
Y y;
return y.get();
}