执行以下代码时出现运行时错误:
#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;
}
我试图找出删除原始共享指针后指针是否仍然可以访问(不应该)。