Help us understand the problem. What is going on with this article?

C++ Shared Pointerのテスト

More than 5 years have passed since last update.

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;
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away