LoginSignup
1
0

More than 5 years have passed since last update.

C++ Shared Pointerのテスト

Posted at

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;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0