#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Hoge {
public:
Hoge() { cout << "Create Hoge!" << endl; }
~Hoge() { cout << "Delete Hoge!" << endl; }
};
int main() {
weak_ptr<Hoge> weakPtr;
{
shared_ptr<Hoge> sharedPtr(new Hoge());
cout << "sharedPtr:" << sharedPtr << endl;
weakPtr = sharedPtr;
// 使用するときは lock() を使って本体があるかを確認
if (shared_ptr<Hoge> tmpPtr = weakPtr.lock()) {
cout << "weakPtr:" << tmpPtr << endl;
} else {
cout << "weakPtr:Nothing!" << endl;
}
}
// 既に sharedPtr は破棄されているので参照先がなくなる!
if (shared_ptr<Hoge> tmpPtr = weakPtr.lock()) {
cout << "weakPtr:" << tmpPtr << endl;
} else {
cout << "weakPtr:Nothing!" << endl;
}
return 0;
}