C++11のshared pointerの振る舞いを調べるコード。
2つのベクターに代入してリファレンスカウントを出力する、
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class X{
int x;
public:
X(int x):x(x){
cout << "constructed" << endl;
};
~X(){
cout << x << " destructed" << endl;
}
};
vector< shared_ptr<X>> globalVect;
void add(shared_ptr<X> &x){
cout << "passed to func" << endl;
cout << "count " << x.use_count() << endl; // 1
vector< shared_ptr<X>> localVect1;
localVect1.push_back(x);
cout << "copy to local vector" << endl;
cout << "count " << x.use_count() << endl; //2
globalVect.push_back(x);
cout << "copy to global vector" << endl;
cout << "count " << x.use_count() << endl; // 3
}
int main(int argc, const char * argv[]) {
auto x = shared_ptr<X>(new X(10));
cout << "shared point created" << endl;
cout << "count " << x.use_count() << endl; // 1
add(x);
cout << "return to main" << endl;
cout << "count " << x.use_count() << endl; // 2
globalVect.erase(globalVect.begin(), globalVect.end());
cout << "deleted from glibal vector" << endl;
cout << "count " << x.use_count() << endl; // 1
x.reset();
cout << "manually realeased" << endl;
cout << "count " << x.use_count() << endl; // 1
return 0;
}