以下のコードを実行すると、ランタイム エラーが発生します。
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Test
{
public:
int value;
Test( )
{
value = 1;
}
~Test( )
{
}
};
int main() {
shared_ptr<Test> pTest = shared_ptr<Test>( new Test( ) );
std::vector<weak_ptr<Test>> testList;
testList.push_back( weak_ptr<Test>(pTest) );
cout << "\n Before Deletion";
for (unsigned int i=0; i < testList.size(); i++)
{
try
{
auto p = testList[i].lock();
cout << "\n Item not null: " << p->value;
}
catch (bad_weak_ptr b)
{
wcout << L"Null object" << endl;
}
}
pTest.reset( );
cout << "\n After Deletion";
for (unsigned int i=0; i < testList.size(); i++)
{
try
{
auto p = testList[i].lock();
cout << "\n Item not null: " << p->value;
}
catch (bad_weak_ptr b)
{
wcout << L"Null object" << endl;
}
}
// your code goes here
return 0;
}
元の共有ポインターを削除した後、ポインターがまだアクセス可能であるかどうか (そうであってはならない) を見つけようとしていました。